我的任务是修复一个当前使用GROUP BY WITH ROLLUP创建总计行的查询。
SELECT CONVERT(date, ShipDate),
DelNum,
SUM(ShipQty),
ROW_NUMBER() OVER(ORDER BY CASE WHEN ShipDate IS NULL THEN 0 ELSE ShipDate END ASC,CASE WHEN DelNum IS NULL THEN 'Z' ELSE DelNum END ASC)
FROM Shipments
WHERE Company = 'ABC' AND CustNum = 3
GROUP BY ShipDate, DelNum, ShipQty WITH ROLLUP
这是我给出的查询。我一直在添加一些标签和一些排序,以使其更具可读性:
SELECT CONVERT(date, ShipDate),
CASE WHEN (GROUPING(DelNum) = 1) THEN 'SUB TOTAL FOR ' + CONVERT(NVARCHAR, ShipDate, 111)
WHEN (GROUPING(ShipQty) = 1) THEN 'SUB TOTAL FOR ' + DelNum
--WHEN (GROUPING(Total) = 1) THEN 'TOTAL'
ELSE ISNULL(DelNum, 'UNKNOWN')
END AS DelNum,
SUM(ShipQty) Total,
ROW_NUMBER() OVER(ORDER BY CASE WHEN ShipDate IS NULL THEN 0 ELSE ShipDate END ASC,CASE WHEN DelNum IS NULL THEN 'Z' ELSE DelNum END ASC)
FROM Shipments
WHERE Company = 'ABC' AND CustNum = 3
GROUP BY ShipDate, DelNum, ShipQty WITH ROLLUP
ORDER BY ShipDate, DelNum, Total ASC
我遇到的问题是我注释掉的那一行。如何标记总行数。我一直认为Total
无法识别。
任何帮助都将不胜感激。
答案 0 :(得分:1)
Total
是列别名,您无法在GROUPING
函数中引用它。您也不能将聚合放在GROUPING
函数中,如下所示:
WHEN (GROUPING(SUM(ShipQty)) = 1)
可以做的是检查所有组字段是否为GROUPING() = 1
:
CASE WHEN (GROUPING(ShipDate) = 1 and GROUPING(DelNum) = 1 and GROUPING(ShipQty) = 1) THEN 'TOTAL'
WHEN (GROUPING(DelNum) = 1) THEN 'SUB TOTAL FOR ' + CONVERT(NVARCHAR, ShipDate, 111)
WHEN (GROUPING(ShipQty) = 1) THEN 'SUB TOTAL FOR ' + DelNum
ELSE ISNULL(DelNum, 'UNKNOWN')
END AS DelNum
请注意,您需要将该检查移至CASE
的顶部,否则CASE
将在评估之前发生短路(因为每个人GROUPING
自己等于1)