案例当带回两行而不是一条

时间:2019-06-10 09:27:17

标签: sql group-by sql-server-2016

大家好,我正在处理一些代码,我确定需要做的相对容易,但是我在Case语句上苦苦挣扎

我需要做什么; 将数据集带回到SSRS中的表格中,按年份,然后按使用月,再按帐单层划分

问题; 计费等级为0、1、4、5 0是历史数据,我需要将其显示为1,然后将0和原始第1层加在一起

我到目前为止所做的;

DECLARE @UsageMonth DATE = '20170401'
DECLARE @YEAR INT = '2017'
DECLARE @BillingTier2 INT = 1;

SELECT  YEAR(UsageMonth) AS [Year],
        UsageMonth,
        --Billingtier,
        CASE WHEN billingtier = 0 THEN 1 ELSE billingtier END AS BillingTier2,
        SuppliesBilled = COUNT(DISTINCT c.CoreMPAN),
        CreditKwH = SUM(CASE WHEN c.IsCredit = 1 THEN c.ConsumptionUnits ELSE 0 END),
        DebitKwH = SUM(CASE WHEN c.IsCredit = 0 THEN c.ConsumptionUnits ELSE 0 END),
        TotalKwh = SUM(c.ConsumptionUnits),
        CreditAmount = SUM(CASE WHEN c.IsCredit = 1 THEN c.ConsumptionAmount ELSE 0 END),
        DebitAmount = SUM(CASE WHEN c.IsCredit = 0 THEN c.ConsumptionAmount ELSE 0 END),
        TotalAmount= SUM(c.ConsumptionAmount),
        UnitRate = SUM(c.ConsumptionAmount) / NULLIF(SUM(c.ConsumptionUnits), 0),
        StandingCharge = SUM(c.StandingChargeAmount),
        CCL = SUM(c.CCLAmount)

FROM    dbo.table1 c
WHERE YEAR(UsageMonth) = @YEAR
AND UsageMonth = @UsageMonth
GROUP BY YEAR(UsageMonth), UsageMonth, Billingtier, CASE WHEN billingtier = 0 THEN 1 ELSE billingtier END

我在这里遇到的问题是,这会将先前为0的所有列都带回一行,以及另一行的计费层实际上为1的行,因此给我两行表示“ 1”,应该是一行,同时将计费等级1和计费等级0相加

预期数据

Year    UsageMonth  BillingTier2    SuppliesBilled  CreditKwH   DebitKwH    TotalKwh    CreditAmount    DebitAmount TotalAmount UnitRate    StandingCharge  CCL
2017    01/04/2017  1   3296    -4348786.008    7219573.706 2870787.699 -523979.1005    866478.4812 342499.3807 0.238118    22394.5114  10685.7546
2017    01/04/2017  4   27  -59415.7663 65843.4963  6427.73 -9269.5841  10359.9353  1090.3512   0.169632    118.5181    21.3836
2017    01/04/2017  5   515 -524035.4192    943647.2675 419611.8483 -105349.1449    189478.524  84129.3791  0.200493    6581.5  1567.7762

数据接收

Year    UsageMonth  BillingTier2    SuppliesBilled  CreditKwH   DebitKwH    TotalKwh    CreditAmount    DebitAmount TotalAmount UnitRate    StandingCharge  CCL
2017    01/04/2017  1   3124    -4348786.008    7219573.706 2870787.699 -523979.1005    866478.4812 342499.3807 0.119305    22394.5114  10685.7546
2017    01/04/2017  4   27  -59415.7663 65843.4963  6427.73 -9269.5841  10359.9353  1090.3512   0.169632    118.5181    21.3836
2017    01/04/2017  5   515 -524035.4192    943647.2675 419611.8483 -105349.1449    189478.524  84129.3791  0.200493    6581.5  1567.7762

如您所见,所有的总和和数据都匹配,计数时,Case语句中缺少最初记为0的耗材(172)

这里的任何帮助将不胜感激

欢呼

1 个答案:

答案 0 :(得分:0)

当您在COUNT函数中使用DISTINCT时,如下所示-

 SuppliesBilled = COUNT(DISTINCT c.CoreMPAN)

如果有多个具有相同值的c.CoreMPAN可用,它将减少COUNT的数量。 e你知道这一点。如果不希望这样做,可以尝试从COUNT中删除DISTINCT命令,如下所示-

 SuppliesBilled = COUNT(c.CoreMPAN)