查询中新列的总和

时间:2018-05-23 09:55:41

标签: sql sql-server sum

我有以下查询:

SELECT distinct COUNT(Status) AS [Transactions], sending_organisation AS [Supplier],
DATENAME(mm, Date_Reported) AS Month, DATENAME(yyyy, Date_Reported) AS Year,
Sum(Case When Status = 'Defect' Then 1 Else 0 End) As Defect,
Sum(Case When Status = 'Failed' Then 1 Else 0 End) As Failed,
Sum(Case When Status = 'Success' Then 1 Else 0 End) As Success,
 FROM [Tx]
 where Channel_Partner = 'CAT'
 and DATENAME(yyyy, Date_Reported) = '2018'
 and DATENAME(mm, Date_Reported) = 'March'
GROUP BY DATENAME(mm, Date_Reported), DATENAME(yyyy, Date_Reported), sending_organisation
ORDER BY sending_organisation ASC

正如您所看到的,我创建了新的缺陷列,成功,失败。

我想在同一查询中添加另一列来查找失败+成功的总和?

如果不创建表或执行多个查询,如何做到这一点?

提前致谢

1 个答案:

答案 0 :(得分:1)

只需添加另一列COUNT(<expr>)

SUM(CASE WHEN [Status] IN ('Success','Failed') THEN 1 ELSE 0 END) AS SuccessFailed

除了OP的意见(完全不相关的事情),要返回当前月份的数据,我将使用:

AND Date_Reported >= DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()),0)
AND Date_Reportded < DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()) + 1,0)

如果需要,您应该能够根据自己的需要轻松改变这种情况。在列上使用DATENAME之类的内容并不是一个好主意;它使查询不具有SARG。