使用case以便使用通配符检索聚合

时间:2017-07-18 14:02:44

标签: sql sql-server

我想选择c。[weight]的总和,其中dc.description是不同的。我希望做5个案例:例如dc.description像'failed%'那样计算c。[寄售参考]的总和。

我该怎么做?

 SELECT lpr.RegID, lpr.Reg,
                        SUM(c.[Weight]) AS LeftOffWt
                FROM    dbo.whsCo wc
                        INNER JOIN whsHe wh on wh.WhsHeaderID = wc.whsHeaderID
                        INNER JOIN dbo.cgtCo c ON c.[Consignment Reference] = wc.ConsignmentReference
                        INNER JOIN dbo.disCo dc on dc.ConsignmentRef = wc.ConsignmentReference
                        INNER JOIN dbo.genA ga ON ga.AddressID = c.Consignor
                        INNER JOIN dbo.lpra lp ON lp.Postcode = ga.PostcodePrefix
                        INNER JOIN dbo.lstPos lpr ON lpr.RegionID = lp.RegionID
                                                          AND c.Cancelled = 0
                WHERE   wc.StatusCode IN ( 'NL' ) and wh.ArrDepDate between @StartDate and @EndDate and dc.Description like '%failed%'
                GROUP BY lpr.RegionID, lpr.Region

1 个答案:

答案 0 :(得分:0)

使用条件聚合 - 即将CASE作为聚合函数SUM()的参数:

SELECT lpr.RegID, lpr.Reg,
       SUM(c.[Weight]) AS LeftOffWt,
       SUM(CASE WHEN dc.description like 'failed%' THEN c.[consignment reference] ELSE 0 END) AS sum_failed,
       . . .
. . .

您还需要从WHERE子句中删除条件。