我在列中的数据为: -
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
...
...
答案 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
,因此您可以使用SWITCH
或IIF
,如下所示:
SUM(IIF(TAT = 'Pass', Volume, 0)) AS Pass