Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 How to sort specific column under GROUPING SETS?

Author  Topic 

dchencm
Starting Member

6 Posts

Posted - 2014-08-21 : 13:07:48
If I remember correctly, in SQL Server, it is not recommended to use "ORDER BY" when there's already a GROUP BY GROUPING SETS.

I have two columns: [UPC#] & [Description] both are varchar.

My grouping sets is like this:

GROUP BY
GROUPING SETS
(
([UPC],[Description])
,()
)


I don't have 'ORDER BY' but it's automatically sorting the Description column.

If I added a 3rd column, sum(Qty), then it doesn't sort by Description anymore. But if I added


ORDER BY [Description]


then the grand total of sum(Qty) will be at the first row instead of the last.

Is there a way to sort the Description column and still let the grand total of sum(Qty) be at the last row instead?

Thanks.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2014-08-21 : 16:22:42
GROUP BY does not sort data. Sets have no order.
Your data will be outputed in the order the CPU processes the groups, which can be different between executions.
Most common when statistics change.

Use ORDER BY GROUPING(...)



Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page
   

- Advertisement -