在SQL Server 2014中使用CTE和UNION ALL

时间:2018-05-06 18:46:54

标签: sql sql-server tsql sql-server-2014

我的问题是:

创建一个显示前5个销售产品的视图,以及显示所有其他产品的总销售额的汇总行以及总计上述所有产品的总计行。

WITH ProductTop5 AS 
(
    SELECT [dbo].[Product].[ProductName] AS ProductName, SUM([dbo].[SalesOrderDetail].[LineTotal]) AS TotalAmount
    FROM [dbo].[Product]
    JOIN [dbo].[SalesOrderDetail] ON [dbo].[Product].[ProductID] = [dbo].[SalesOrderDetail].[ProductID]
    GROUP BY [dbo].[Product].[ProductName]  
)

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER/RANK来计算产品的排名:

WITH Product AS 
(
    SELECT p.[ProductName] AS ProductName,
           SUM(sod.[LineTotal]) AS TotalAmount
    FROM [dbo].[Product] p
    JOIN [dbo].[SalesOrderDetail] sod 
      ON p.[ProductID] = sod.[ProductID]
    GROUP BY p.[ProductName]  
), ProductWithRank AS (
    SELECT ProductName, Total_Amount,
           ROW_NUMBER() OVER(ORDER BY Total_Amount DESC) AS rn
    FROM Product
)
SELECT ProductName, TotalAmount
FROM ProductWithRank
WHERE rn <= 5
UNION ALL
SELECT 'All Others', SUM(Total_Amount)
FROM ProductWithRank
WHERE rn > 5
UNION ALL
SELECT 'Grand Total', SUM(TotalAmount)
FROM ProductWithRank;