使用具有多个条件的sql获得总和

时间:2012-07-30 13:45:40

标签: sql ms-access

我在列中的数据为: -

  Process   Volume      TAT
  1            1        Pass
  1            2        Fail
  2            5        Fail
  2            5        Pass
  3            1        Pass
  4            6        Fail
  4            4        Pass

现在按进程分组,我想要音量总和(不考虑任何TAT),TAT =通过的音量总和,TAT =失败的音量总和。

喜欢这个

Process     Total Volume    Volume(TAT=Pass)    Volume(TAT = Fail)
1           3               1                   2
2           10              5                   5
...
...

1 个答案:

答案 0 :(得分:6)

对于SQL Server,您可以使用CASE表达式有条件地确定需要添加的金额,然后SUM将它们组合在一起,如下所示:

SELECT Process, SUM(Volume) AS TotalVolume, 
    SUM(CASE WHEN TAT = 'Pass' THEN Volume ELSE 0 END) AS Pass,
    SUM(CASE WHEN TAT = 'Fail' THEN Volume ELSE 0 END) AS Fail
FROM (
     -- Dummy data here for testing
    SELECT 1 AS Process, 1 as Volume, 'Pass' AS TAT
    UNION SELECT 1, 2, 'Fail'
    UNION SELECT 2, 5, 'Fail'
    UNION SELECT 2, 5, 'Pass'
    UNION SELECT 3, 1, 'Pass'
    UNION SELECT 4, 6, 'Fail'
    UNION SELECT 4, 4, 'Pass'
) MyTable
GROUP BY Process
ORDER BY Process

对于Microsoft Access,不支持CASE,因此您可以使用SWITCHIIF,如下所示:

SUM(IIF(TAT = 'Pass', Volume, 0)) AS Pass