SQL条件计算

时间:2011-09-14 20:55:15

标签: sql-server sql-server-2008

我有3张桌子。他们有一对多的关系

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
        table3 ON table2.secID = table3.secID
GROUP BY table1.mainID HAVING table1.mainID =11

以下查询有效,但给了我所有的总和。

如何根据条件获取SUM?即

S00 = SUM(table3.Num00) if table1.Select00 = 1 (true)
S01 = SUM(table3.Num01) if table1.Select01 = 1 (true)

1 个答案:

答案 0 :(得分:5)

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;