从SUM函数中排除条件SQL Server 2014

时间:2016-10-25 16:31:18

标签: sql sql-server sum sql-server-2014

我对SQL很新,我似乎无法想出一种方法来产生我想要的结果。我试图通过老化桶和设施获得所有A / R桶的总和。在桶内有几个不同的类别(保险,Lien& Pt。责任)我想在SUM中包括所有类别,除了" Lien"。我一直收到GROUP BY聚合错误。有人可以帮忙吗?谢谢!

SELECT ar.[Report Date]
,ar.Facility
,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN SUM (ar.[0-30]) END) AS [0-30]
,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN SUM (ar.[31-60]) END) AS [31-60]
,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN SUM (ar.[61-90]) END) AS [61-90]
,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN SUM (ar.[91-120] + ar.[120+]) END) AS [91+]
FROM DBO.ARByPayer AS ar
GROUP BY ar.Facility, ar.[Report Date]

2 个答案:

答案 0 :(得分:0)

您可以使用子查询来实现它。

Select [Report Date], Facility,  sum([0-30]) AS [0-30], sum([31-60]) AS [31-60], sum([61-90]) AS [61-90], sum([91+]) AS [91+]
        (SELECT ar.[Report Date]
        ,ar.Facility
        ,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN ar.[0-30] END) AS [0-30]
        ,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN ar.[31-60] END) AS [31-60]
        ,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN ar.[61-90] END) AS [61-90]
        ,(CASE WHEN ar.[Current Financial Class] <> 'Lien' THEN ar.[91-120] + ar.[120+]) END) AS [91+]
        FROM DBO.ARByPayer AS ar) t
        GROUP BY Facility, [Report Date]

答案 1 :(得分:0)

您应该使用where子句从查询中排除这些行。

SELECT ar.[Report Date]
    , ar.Facility
    , SUM (ar.[0-30]) AS [0-30]
    , SUM (ar.[31-60]) AS [31-60]
    , SUM (ar.[61-90]) AS [61-90]
    , SUM (ar.[91-120] + ar.[120+]) AS [91+]
FROM DBO.ARByPayer AS ar
WHERE ar.[Current Financial Class] <> 'Lien'
GROUP BY ar.Facility
    , ar.[Report Date]