質問

When using ROLLUP in SQL server, how can I get the subtotal rows above the detailed rows?

This is what you would usually get when using 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

This is the expected Result set:

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

Query used:

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

Any ideas how we could get this output?

役に立ちましたか?

解決

You don't explicitly order the results so when you say this is what you would usually get ... sub total row for Europe appears after all the individual rows for Europe you're just getting lucky.

Try ordering your result set:

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

Although also try not using WITH ROLLUP as well:

Non-ISO Compliant Syntax

...

WITH ROLLUP

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top