我有这个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
...
答案 0 :(得分:2)
其他答案错误地代表了你想要的东西。
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;