2012-05-08 36 views
3

如何將結果按賣家姓名排序到以下示例中,同時保持彙總在底部?如何在保持彙總在最後一行的同時對嵌套select的結果進行排序?

由於該分組適用於嵌套的SELECT我不能使用ORDER BY並且由於分組未應用於頂層,所以我也不能使用GROUPING

Click here to see the working example in SQL Fiddle.

CREATE TABLE Sales 
(
     SellerID INT 
    , StoreID  INT 
    , Price  MONEY 
); 

CREATE TABLE Sellers 
(
     SellerID INT 
    , Name  VARCHAR(50) 
) 

INSERT INTO Sales VALUES 
    (1, 1, 100), 
    (1, 1, 100), 
    (1, 1, 100), 
    (2, 2, 200), 
    (2, 2, 200), 
    (3, 2, 250), 
    (3, 2, 250), 
    (3, 2, 250), 
    (3, 2, 250); 

INSERT INTO Sellers VALUES 
    (1, 'C. Thirdplace'), 
    (2, 'A. Firstplace'), 
    (3, 'B. Secondplace'); 

SELECT s.Name   AS Seller_Name 
    , x.TotalSales AS Total_Sales 
FROM 
( 
    SELECT  s.SellerID AS SellerID 
      , SUM(s.Price) AS TotalSales 
    FROM  Sales s 
    GROUP BY s.SellerID 
    WITH ROLLUP 
) x 
LEFT JOIN Sellers s 
ON   s.SellerID = x.SellerID; 

將會產生以下結果:

SELLER_NAME  TOTAL_SALES 
--------------- ----------- 
C. Thirdplace  300 
A. Firstplace  400 
B. Secondplace  1000 
(null)    1700 

回答

4
ORDER BY 
    CASE WHEN seller_name IS NULL THEN 1 ELSE 0 END, 
    seller_name 
+0

很好的解決方案!但是如果彙總被認爲是最後一次,它是否應該與0/1相反? – altschuler

+0

@altschuler - 排序自然是上升的。這使NULL最後。 – MatBailie

+0

但是在這裏,如果它的彙總和「0,」如果其他的,或者我錯過了什麼,您在這裏訂購的是「1,null」? – altschuler

相關問題