Here's my SQL:
;Test1 AS ( SELECT C1.Col1 , C1.Col2 , C1.Col3 , C1.Col4 , [Status] = ( SELECT CASE WHEN [Status] IN ( 'Ind' ,'Act' ,'Bor' ) AND Col4 = 'Activated' THEN 'Dispose' ELSE [Status] END ) , C1.Col5 , CASE WHEN C1.Col2 = 'Used' Then C1.Col5 ELSE 0 END AS [UCost] , CASE WHEN C1.Col2 = 'Borrowed' Then C1.Col5 ELSE 0 END AS [BCost] FROM Cted C1 AND [Status] IN ( 'ABC', 'DEF', 'GHI', 'Dispose' ) ) Select C2.Col1 , C2.Col3 , SUM(Case When C2.Status = 'ABC' Then 1 Else 0 End) As [Tr1] , SUM(Case When C2.Status = 'DEF' Then 1 Else 0 End) As [Tr2] , SUM(Case When C2.Status = 'GHI' Then 1 Else 0 End) As [Tr3] , SUM(Case When C2.Status = 'Dispose' Then 1 Else 0 End) As [Tr4] , SUM(UCost) As Cost1 -- Gives me wrong results, seems to multiply the cost twice , SUM(BCost) As Cost2 -- Gives me wrong results, seems to multiply the cost twice From Test1 C2 Group By C2.Col1, C2.Col3 Order By C2.Col1
When I run my query the SUM of my cost is giving me wrong results. Can you direct me in a right direction? I want just 1 row for each Col1 (I am getting that), the columns are getting loaded properly, but its just the cost column that's giving me a trouble.