SQL 中没有总计的 ORDER BY

ORDER BY without Total in SQL

我有这个 SQL 查询,它使用 ROLLUP 来获取总数,但还需要按金额对每隔一​​行进行排序:

SELECT 
    ISNULL([SharepointId], 'Total') as 'Sharepoint', 
    Count([Id]) as 'Nombre de tickets' 
FROM [dbo].[Tickets]
GROUP BY ROLLUP([SharepointId])
ORDER BY 2 DESC, 1

有没有办法确保总计位于结果的末尾,同时保持其他行的降序?

现在,这是我得到的:

Sharepoint         Nombre de tickets
------------------ -----------------
Total              20326
INTERNE            9396
MAIN               1503
...

修改 Order By 子句如下:

CASE WHEN  ISNULL([SharepointId], 'Total') <>'Total' THEN  
Count([Id])END DESC, 1

试试这个

SELECT 
    ISNULL([SharepointId], 'Total') as [Sharepoint], 
    Count([Id]) as [Nombre de tickets]
FROM [dbo].[Tickets]
GROUP BY ROLLUP([SharepointId])
ORDER BY CASE WHEN [SharepointId] IS NULL THEN 'B' ELSE 'A' END, [Nombre de tickets] DESC

简单使用case表达式:

order by (case when SharepointId is null then 1 else 0 end), [Nombre de tickets] desc;

其他答案错误地表达了您想要的内容。

  • 您不希望最后一行因为它是 NULL
  • 您希望最后一行是因为它已被分组


SQL 服务器有一个功能,文档页面几乎完全包含您的示例...


SELECT 
    ISNULL([SharepointId], 'Total') as 'Sharepoint', 
    Count([Id]) as 'Nombre de tickets' 
FROM [dbo].[Tickets]
GROUP BY ROLLUP([SharepointId])
ORDER BY GROUPING([SharepointId]), 2 DESC

GROUPING([SharepointId])0 当列 分组时 (因此这些行首先排序) 并且然后它是 1,当列 分组时 (因此该行排在最后)。这在汇总多列时特别有用。