0

假设我在 SQL Server 2008 R2 中有一个Purchase用两列调用的表:PurchaserExpenditure.

假设该表具有以下行:

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和在组行中按升序排列。7008001000

谁能建议什么查询会返回这个结果集?

4

1 回答 1

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;
于 2012-05-04T03:21:31.527 回答