[英]getting sum using sql with multiple conditions
I m having data in columns as: - 我在列中的数据如下:-
Process Volume TAT
1 1 Pass
1 2 Fail
2 5 Fail
2 5 Pass
3 1 Pass
4 6 Fail
4 4 Pass
Now grouping by Process, i want the sum of volume (not taking into account whatever TAT), sum of volume where TAT = Pass, sum of Volume where TAT = Fail. 现在按流程分组,我想要的数量总和(不考虑任何TAT),TAT =通过的数量总和,TAT =失败的数量总和。
Like this 像这样
Process Total Volume Volume(TAT=Pass) Volume(TAT = Fail)
1 3 1 2
2 10 5 5
...
...
For SQL Server, you can use CASE
expressions to conditionally determine the amount you need to add, then SUM
them together, like this: 对于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
For Microsoft Access, CASE
isn't supported, so you can use SWITCH
or IIF
, like so: 对于Microsoft Access,不支持CASE
,因此可以使用SWITCH
或IIF
,如下所示:
SUM(IIF(TAT = 'Pass', Volume, 0)) AS Pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.