SQL 服务器总计出现在第一行而不是 table 末尾时出错
Error when SQL Server grand total comes out on first row instead of at table end
以下查询获取行和列的总计。当我添加 ORDER BY 时,列总计出现在第一行而不是底行。您建议的解决方案是什么?
Select
isnull (Definition_, 'GrandTotal') AS 'Definition_',
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 1 THEN OrderQty END),0) AS January,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 2 THEN OrderQty END),0) AS Feburary,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 3 THEN OrderQty END),0) AS March,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 4 THEN OrderQty END),0) AS April,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 5 THEN OrderQty END),0) AS May,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 6 THEN OrderQty END),0) AS June,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 7 THEN OrderQty END),0) AS July,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 8 THEN OrderQty END),0) AS August,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 9 THEN OrderQty END),0) AS September,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 10 THEN OrderQty END),0) AS October,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 11 THEN OrderQty END),0) AS November,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 12 THEN OrderQty END),0) AS December,
isnull (SUM(OrderQty),0) AS GrandTotal,
FROM Production.WorkOrder
GROUP BY GROUPING SETS((DATEPART(YEAR, DueDate), Definition_, ProductID),
())order by ProductID;
您可以使用 grouping
which returns 1 如果该列是聚合的一部分并且您可以通过以下方式在您的订单中使用它:
...
order by grouping(ProductID)
,grouping(Definition_)
,grouping(DATEPART(YEAR, DueDate))
,ProductID;
以下查询获取行和列的总计。当我添加 ORDER BY 时,列总计出现在第一行而不是底行。您建议的解决方案是什么?
Select
isnull (Definition_, 'GrandTotal') AS 'Definition_',
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 1 THEN OrderQty END),0) AS January,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 2 THEN OrderQty END),0) AS Feburary,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 3 THEN OrderQty END),0) AS March,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 4 THEN OrderQty END),0) AS April,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 5 THEN OrderQty END),0) AS May,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 6 THEN OrderQty END),0) AS June,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 7 THEN OrderQty END),0) AS July,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 8 THEN OrderQty END),0) AS August,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 9 THEN OrderQty END),0) AS September,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 10 THEN OrderQty END),0) AS October,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 11 THEN OrderQty END),0) AS November,
isnull (SUM(CASE DATEPART(MONTH,DueDate) WHEN 12 THEN OrderQty END),0) AS December,
isnull (SUM(OrderQty),0) AS GrandTotal,
FROM Production.WorkOrder
GROUP BY GROUPING SETS((DATEPART(YEAR, DueDate), Definition_, ProductID),
())order by ProductID;
您可以使用 grouping
which returns 1 如果该列是聚合的一部分并且您可以通过以下方式在您的订单中使用它:
...
order by grouping(ProductID)
,grouping(Definition_)
,grouping(DATEPART(YEAR, DueDate))
,ProductID;