假设我在SQL Server 2008 R2中有一个名为Purchase
的表,其中有两列:Purchaser
和Expenditure
。
假设该表格包含以下行:
Purchaser Expenditure
--------- -----------
Alex 200
Alex 300
Alex 500
Bob 300
Bob 400
Charlie 200
Charlie 600
Derek 100
Derek 300
现在我有了这个问题:
SELECT Purchaser, Expenditure, SUM(Expenditure) AS SumExpenditure FROM Purchase GROUP BY Purchaser, Expenditure WITH ROLLUP
返回以下内容:
Purchaser Expenditure SumExpenditure
--------- ----------- --------------
Alex 200 200
Alex 300 300
Alex 500 500
--------------------------------
Alex NULL 1000
--------------------------------
Bob 300 300
Bob 400 400
--------------------------------
Bob NULL 700
--------------------------------
Charlie 200 200
Charlie 600 600
--------------------------------
Charlie NULL 800
--------------------------------
Derek 100 100
Derek 300 300
--------------------------------
Derek NULL 400
--------------------------------
(添加了一些行以强调累计金额。)
我希望能够按分组数量对组进行排序,以便最终得到如下结果集:
Purchaser Expenditure SumExpenditure
--------- ----------- --------------
Derek 100 100
Derek 300 300
--------------------------------
Derek NULL 400
--------------------------------
Bob 300 300
Bob 400 400
--------------------------------
Bob NULL 700
--------------------------------
Charlie 200 200
Charlie 600 600
--------------------------------
Charlie NULL 800
--------------------------------
Alex 200 200
Alex 300 300
Alex 500 500
--------------------------------
Alex NULL 1000
--------------------------------
换句话说,我正在使用组行中的400
,700
,800
和1000
按升序对组进行排序。
有人可以建议哪些查询会返回此结果集吗?
答案 0 :(得分:0)
;WITH x AS
(
SELECT Purchaser, Expenditure, s = SUM(Expenditure)
FROM dbo.Purchase
GROUP BY Purchaser, Expenditure WITH ROLLUP
),
y AS
(
SELECT Purchaser, s FROM x
WHERE Expenditure IS NULL
AND Purchaser IS NOT NULL
),
z AS
(
SELECT Purchaser, s, rn = ROW_NUMBER() OVER (ORDER BY s)
FROM y
)
SELECT x.Purchaser, x.Expenditure, x.s FROM x
INNER JOIN z ON x.Purchaser = z.Purchaser
ORDER BY z.rn, CASE WHEN z.s IS NULL THEN 2 ELSE 1 END;