DECLARE @t TABLE(Groups char(2),Item varchar(10),Color varchar(10),Quantity int)
INSERT @t SELECT 'aa','Table','Blue', 124
UNION ALL SELECT 'bb','Table','Red', -23
UNION ALL SELECT 'bb','Cup' ,'Green',-23
UNION ALL SELECT 'aa','Chair','Blue', 101
UNION ALL SELECT 'aa','Chair','Red', -90
--统计及排序
SELECT Groups,Item,Color,
Quantity=SUM(Quantity)
FROM @t
GROUP BY Groups,Item,Color WITH ROLLUP
ORDER BY GROUPING(Groups),Groups DESC, --保证一级分组数据的顺序
GROUPING(Item),Item DESC, --保证二级分组数据的顺序
GROUPING(Color),Color DESC, --保证三级分组数据的顺序
Quantity DESC --从这里开始为用户定义的排序
/*--结果
Groups Item Color Quantity
--------- -------------- --------------- -----------
bb Table Red -23
bb Table NULL -23
bb Cup Green -23
bb Cup NULL -23
bb NULL NULL -46
aa Table Blue 124
aa Table NULL 124
aa Chair Red -90
aa Chair Blue 101
aa Chair NULL 11
aa NULL NULL 135
NULL NULL NULL 89
--*/