当 SQL Server 总计出现在第一行而不是表末尾时出错

Posted

技术标签:

【中文标题】当 SQL Server 总计出现在第一行而不是表末尾时出错【英文标题】:Error when SQL Server grand total comes out on first row instead of at table end 【发布时间】:2021-09-03 13:02:10 【问题描述】:

以下查询获取行和列总计。当我添加 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;

【问题讨论】:

【参考方案1】:

您可以使用grouping,如果该列是聚合的一部分,则返回 1,您可以通过以下方式在您的订单中使用它:

...
order by grouping(ProductID) 
        ,grouping(Definition_)
        ,grouping(DATEPART(YEAR, DueDate))
        ,ProductID;

【讨论】:

以上是关于当 SQL Server 总计出现在第一行而不是表末尾时出错的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 报表生成器 - 仅显示运行总计

SQL Server - 连接表,使多行变成一行

SQL Server游标

更新表以按分组列显示总计 SQL Server 2008 R2

在 SQL Server 中计算运行总计

按SQL Server中的总计百分比分组