SQL Server:ROLLUP

sla*_*oah 2 sql sql-server rollup

ROLLUP在SQL Server中使用时,如何获取详细行上方的小计行?

这是您在使用时通常会得到的ROLLUP:

Group                Name                 Total Sales
----------------     ---------------      ------------
Europe               France                74569.00
Europe               Germany               59456.00
Europe               United Kingdom        78327.00
Europe               NULL                 212352.00        << sub total row for Europe appears **after** all the individual rows for Europe.
North America        Northwest            208774.00
North America        Southeast            145477.00
North America        Southwest            164232.00
North America        NULL                 518483.00
Pacific              Australia             93403.00
Pacific              NULL                  93403.00
Run Code Online (Sandbox Code Playgroud)

这是预期的结果集:

Group                Name                 Total Sales
----------------     ---------------      ------------
Europe               NULL                 212352.00        << sub total row for Europe needs to appear **before** the individual rows for Europe.
Europe               France                74569.00
Europe               Germany               59456.00
Europe               United Kingdom        78327.00
North America        NULL                 518483.00
North America        Northwest            208774.00
North America        Southeast            145477.00
North America        Southwest            164232.00
Pacific              NULL                  93403.00
Pacific              Australia             93403.00
Run Code Online (Sandbox Code Playgroud)

使用的查询:

SELECT      [Group], [Name], SUM([SalesYTD]) AS 'Total Sales'
FROM        #TempTable
GROUP BY    [Group], [Name] WITH ROLLUP 
Run Code Online (Sandbox Code Playgroud)

有什么想法我们如何获得这个输出?

ta.*_*.is 6

您没有明确地对结果进行排序,因此当您说这是您通常会得到的结果时......欧洲的所有单行都出现在欧洲的子总行之后,您就会变得幸运.

尝试订购结果集:

SELECT      [Group], [Name], SUM([SalesYTD]) AS 'Total Sales'
FROM        #TempTable
GROUP BY    [Group], [Name] WITH ROLLUP 
ORDER BY    [Group], [Name]
Run Code Online (Sandbox Code Playgroud)

虽然也尽量不使用WITH ROLLUP,以及:

非ISO兼容语法

...

与ROLLUP

将在Microsoft SQL Server的未来版本中删除此功能.避免在新的开发工作中使用此功能,并计划修改当前使用此功能的应用程序.