If this is your first visit, be sure to check out the FAQ by clicking the link above.
You may have to register before you can post: click the register link above to proceed.
To start viewing messages, select the forum that you want to visit from the selection below.
SELECT ids.id
,COALESCE(gl.account, '-') as gl_AccountNum
,COALESCE(ic.account, '-') as ic_AccountNum
,COALESCE(os.account, '-') as os_AccountNum
FROM (SELECT DISTINCT ID
FROM #DaTable
) AS ids
LEFT OUTER JOIN #DaTable as gl ON
ids.id = gl.id AND
gl.Acc_Type = 'gl'
LEFT OUTER JOIN #DaTable as ic ON
ids.id = ic.id AND
ic.Acc_Type = 'ic'
LEFT OUTER JOIN #DaTable as os ON
ids.id = os.id AND
os.Acc_Type = 'os'
__________________
With kind regards . . . . . SQL Server 2000/2005/2008/2008 R2 Earned beers: 16
Wim
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald Knuth
Grabel's Law: 2 is not equal to 3 -- not even for very large values of 2. Pat Phelan's Law: 2 very definitely CAN equal 3 -- in at least two programming languages
SELECT id
, MAX(CASE WHEN type = 'gl'
THEN accountnum
ELSE NULL END) AS gl_accountnum
, MAX(CASE WHEN type = 'ic'
THEN accountnum
ELSE NULL END) AS ic_accountnum
, MAX(CASE WHEN type = 'os'
THEN accountnum
ELSE NULL END) AS os_accountnum
FROM daTable
GROUP
BY id
I compared your solution with mine (Estimated Execution Plan).
- LEFT OUTER JOIN solution : 63% relative execution cost
- GROUP BY solution : 37% relative execution cost
Yours is definitely the winner.
__________________
With kind regards . . . . . SQL Server 2000/2005/2008/2008 R2 Earned beers: 16
Wim
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald Knuth
Grabel's Law: 2 is not equal to 3 -- not even for very large values of 2. Pat Phelan's Law: 2 very definitely CAN equal 3 -- in at least two programming languages
it's a technique that also has the benefit of working when there is (incorrectly?) more than one row of an account type, which would blow up the join solution
SELECT id
, MAX(CASE WHEN type = 'gl'
THEN accountnum
ELSE NULL END) AS gl_accountnum
, MAX(CASE WHEN type = 'ic'
THEN accountnum
ELSE NULL END) AS ic_accountnum
, MAX(CASE WHEN type = 'os'
THEN accountnum
ELSE NULL END) AS os_accountnum
FROM daTable
GROUP
BY id