I have 3 tables. They have 1 to many relations
table1 - mainID, Select00(bit), Select01(bit)
table2 - secID, mainID
table3 - secID, Num00, Num01
SELECT table1.mainID , SUM(table3.Num00) as S00, SUM(table3.Num01) as S01
FROM table1 INNER JOIN
table2 ON table1.mainID = table2.mainID INNER JOIN
开发者_StackOverflow社区 table3 ON table2.secID = table3.secID
GROUP BY table1.mainID HAVING table1.mainID =11
The following query works, but gives me all sums.
How do I get the SUMs based on condition? i.e
S00 = SUM(table3.Num00) if table1.Select00 = 1 (true)
S01 = SUM(table3.Num01) if table1.Select01 = 1 (true)
SELECT
t1.mainID,
S00 = SUM(CASE WHEN t1.Select00 = 1 THEN t3.Num00 ELSE 0 END),
S01 = SUM(CASE WHEN t1.Select01 = 1 THEN t3.Num01 ELSE 0 END)
FROM
dbo.table1 AS t1
INNER JOIN dbo.table2 AS t2
ON t1.mainID = t2.mainID
INNER JOIN dbo.table3 AS t3
ON t2.secID = t3.secID
WHERE t1.MainID = 11
GROUP BY table1.mainID;
精彩评论