SQL不会完全是GROUP BY

时间:2017-08-09 15:15:57

标签: sql sql-server

我有一个最初工作得很好的SQL代码,但后来我不得不在CASE中添加一个新项目,现在我的GROUP BY不会像以前一样完全组合在一起,这会弄乱我的计算。我甚至不想按照完成的日期进行分组,它只是针对一个案例,但如果我没有它,我的代码就会爆炸。

编辑:原始代码运行良好,但我必须添加完成的日期,以便我可以添加一个CASE,如果我不将它添加到GROUP BY,它会出错,所以我添加了它,现在它没有' t分组它在原始代码中的方式。 这段代码的作用是从其他表中获取大量信息,它计算出有人欠多少钱,有多少人支付并吐出差异。

原始代码

INSERT INTO #ThisReportAll (CustomerID,Year,OverdueBalance,YearSetupId)
SELECT t.CustomerId, ys.Name AS Year,SUM(t.TtlSpeciesCost) - Isnull(cp.TtlPayments,0) + Isnull(ba.Amount,0) 
AS TtlOwnerCost, t.YearSetupId AS YearSetupId
FROM #TotalAnimalCostAll t
LEFT JOIN #CustomerPaymentsAll cp ON t.CustomerId=cp.CustomerID
LEFT JOIN YearSetup ys ON t.YearSetupId = ys.YearSetupId
LEFT JOIN #BalanceAdjustmentsAll ba ON t.CustomerId=ba.CustomerID
GROUP BY t.CustomerId,ys.Name,cp.TtlPayments, ba.Amount, t.YearSetupId

无法正常使用的新代码

INSERT INTO #ThisReportAll (CustomerID,Year,OverdueBalance,YearSetupId)
SELECT t.CustomerId, ys.Name AS Year, 
CASE 
        WHEN SUM(t.TtlSpeciesCost) < 5 AND t.Complete < CONVERT(DATE,'01-01-2017')
        THEN (5) - Isnull(cp.TtlPayments,0) + Isnull(ba.Amount,0) 
        ELSE SUM(t.TtlSpeciesCost) - Isnull(cp.TtlPayments,0) + Isnull(ba.Amount,0) 
END
AS TtlOwnerCost, t.YearSetupId AS YearSetupId
FROM #TotalAnimalCostAll t
LEFT JOIN #CustomerPaymentsAll cp ON t.CustomerId=cp.CustomerID
LEFT JOIN YearSetup ys ON t.YearSetupId = ys.YearSetupId
LEFT JOIN #BalanceAdjustmentsAll ba ON t.CustomerId=ba.CustomerID
GROUP BY t.CustomerId,ys.Name,cp.TtlPayments, ba.Amount, t.YearSetupId, t.Complete

2 个答案:

答案 0 :(得分:3)

我发现您还在新代码中按t.Complete分组,但在原始代码中没有分组。您的结果需要考虑到这一点,否则就会出错。

对我来说,Isnull(cp.TtlPayments,0) + Isnull(ba.Amount,0)在你的CASE语句中也很奇怪,但当语句在其他地方使用SUM时,它们不是聚合。

答案 1 :(得分:2)

如果您不希望Complete影响您的GROUP BY,则需要在不选择CASE的子查询中执行Complete。然后,您不会在您要分组的数据中添加额外字段。像这样:

SELECT [whatever fields]
from
    (
    SELECT t.CustomerId, ys.Name AS Year, 
    CASE 
        WHEN SUM(t.TtlSpeciesCost) < 5 AND t.Complete < CONVERT(DATE,'01-01-2017')
        THEN (5) - Isnull(cp.TtlPayments,0) + Isnull(ba.Amount,0) 
        ELSE SUM(t.TtlSpeciesCost) - Isnull(cp.TtlPayments,0) + Isnull(ba.Amount,0) 
    END
    AS TtlOwnerCost, t.YearSetupId AS YearSetupId
    FROM #TotalAnimalCostAll t
    LEFT JOIN #CustomerPaymentsAll cp ON t.CustomerId=cp.CustomerID
    LEFT JOIN YearSetup ys ON t.YearSetupId = ys.YearSetupId
    LEFT JOIN #BalanceAdjustmentsAll ba ON t.CustomerId=ba.CustomerID
    ) as a
GROUP BY a.CustomerId, a.Name,a.TtlPayments, a.Amount, a.YearSetupId