3

如何将结果按卖家名称排序到以下示例中,同时将汇总保持在底部?

由于分组应用于嵌套SELECT我无法使用ORDER BY,并且由于分组未应用于顶层,因此我也无法使用GROUPING

单击此处查看 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

1 回答 1

4
ORDER BY
  CASE WHEN seller_name IS NULL THEN 1 ELSE 0 END,
  seller_name
于 2012-05-08T12:04:09.103 回答