How to execute join statement dynamically without using static group id?

All we need is an easy explanation of the problem, so here it is.

I work on SQL server 2014 I need to run this statement below dynamically without

using group id static

because I don’t know maximum group id using may be 10,15,20

so How to run query below dynamically without write static group id on join?

   select r1.familyid, r1.companyid, r1.GlobalPnId,
         ) as PartNumber
 from GetFinalResult r1
 left join GetFinalResult r2 on r2.familyid = r1.familyid and r2.GroupID = 2
 left join GetFinalResult r3 on r3.familyid = r1.familyid and r3.GroupID = 3
 left join GetFinalResult r4 on r4.familyid = r1.familyid and r4.GroupID = 4
 left join GetFinalResult r5 on r5.familyid = r1.familyid and r5.GroupID = 5
 left join GetFinalResult r6 on r6.familyid = r1.familyid and r6.GroupID = 6
 left join GetFinalResult r7 on r7.familyid = r1.familyid and r7.GroupID = 7
 left join GetFinalResult r8 on r8.familyid = r1.familyid and r8.GroupID = 8
 left join GetFinalResult r9 on r9.familyid = r1.familyid and r9.GroupID = 9
 where r1.GroupID = 1

SQL fiddle I will work on it

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I would start with selecting the cte into a temp table an indexing it accordingly, then replacing all the calls to cte for the temp table

You are calling the cte, which is quite complex", multiple times and it has to be evaluated every single time….

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply