Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Trying to add up case statements

Author  Topic 

kcarbone1970
Yak Posting Veteran

52 Posts

Posted - 2014-03-13 : 21:14:43
Hello, I've been working on this query where I am trying to produce a single value the sum of all the case statements. Unfortunately on occasion it produces two records. Im thinking union all?



SELECT A + B + C AS total

FROM ( SELECT DISTINCT
MAX( CASE WHEN CRS.CN IN ( 'G21021', 'G21022', 'G21031',
'G21032', 'G21000', 'G21011',
'G21012' )
AND TST.PT = 1
AND TST.RS < 3 THEN 1
ELSE 0
END ) AS A,
MAX ( CASE WHEN CRS.CN IN ( 'G22021', 'G22022', 'G22031',
'G22032', 'G22000', 'G22001',
'G22002' )
AND TST.PT = 2
AND TST.RS < 3 THEN 2
ELSE 0
END ) AS B,
MAX ( CASE WHEN TST.PT IN ( 1, 2 )
AND TST.RS >= 3
AND CRS.CN NOT IN ( 'G21021', 'G21022',
'G21031', 'G21032',
'G21000', 'G21011',
'G21012', 'G22021',
'G22022', 'G22031',
'G22032', 'G22000',
'G22001', 'G22002' )
THEN 4
ELSE 0
END ) AS C
FROM MST
INNER JOIN STU
INNER JOIN SEC ON STU.SC = SEC.SC
AND STU.SN = SEC.SN ON MST.SC = SEC.SC
AND MST.SE = SEC.SE
INNER JOIN CRS ON MST.CN = CRS.CN
INNER JOIN TST ON STU.ID = TST.PID
WHERE ( SEC.DEL = 0 )
AND ( TST.ID IN ( 'DST' ) )
AND ( TST.TA = 313 )
AND ( STU.ID = 4066398 )
AND ( STU.SC = 20 )
GROUP BY CRS.CN

) AS d



Cartesian Yak

ScottPletcher
Aged Yak Warrior

550 Posts

Posted - 2014-03-14 : 15:39:53
If you want to add all the results from the inner query, just do this:

SELECT SUM(A + B + C) AS total
...
Go to Top of Page
   

- Advertisement -