在SQL中没有Total的ORDER BY

时间:2018-05-16 09:56:13

标签: sql sql-server group-by sql-order-by rollup

我有这个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
...

4 个答案:

答案 0 :(得分:2)

其他答案错误地代表了你想要的东西。

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


SQL Server有一个完全相同的功能,而docs页面几乎就是你的例子......


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 分组(以便该行最后一次)。这在卷起多列时特别有用。

答案 1 :(得分: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

答案 2 :(得分:0)

修改Order By子句,如下所示:

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

答案 3 :(得分:0)

简单使用case表达式:

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