如何向GROUPING_ID结果添加过滤器?

时间:2017-09-01 22:32:08

标签: tsql sql-server-2012

我有以下查询...

SELECT a.countryRegion, a.Stateprovince, SUM (soh.TotalDue) AS revenue,
CASE
WHEN GROUPING_ID(a.countryregion,a.stateprovince) = 0 THEN 'State/Province'
WHEN GROUPING_ID(a.countryregion,a.stateprovince) = 3 THEN 'Total'
WHEN GROUPING_ID(a.countryregion,a.stateprovince) = 1 THEN  'Country Total'
ELSE N'unknown'
END AS 'Level'
FROM saleslt.address AS a
JOIN saleslt.customeraddress AS ca
ON a.addressID = ca.addressID
JOIN saleslt.customer AS c
ON ca.customerID = c.customerID
JOIN salesLT.salesorderheader as soh 
ON c.customerID = soh.customerID
GROUP BY ROLLUP(a.countryregion, a.stateprovince)
ORDER BY  a.countryregion,a.stateprovince;

如何让Country的行包含值'United States Subtotal',以及州/省的行包含值'California Subtotal'?例如?

该表包括大约8个不同的州/省和多个国家。

1 个答案:

答案 0 :(得分:1)

您的GROUP BY ROLLUP(a.countryregion, a.stateprovince)语句应该在小计之前返回NULL值的字段。

您可以将这些NULL值替换为" Sub Total:"通过更改您的选择语句如下:

SELECT 
    coalesce(a.countryRegion,"Sub Total:") as countryRegion,
    coalesce(a.Stateprovince, "Sub Total:") as Stateprovince, .............

您可以格式化报表输出以删除重复的小计,或使用子查询来清理重复。

您可以查看LEAD()和LAG()窗口函数,以获取上一行的countryRegionStateProvince