我有一个查询:(使用一个非常简单的例子)
SELECT
ItemCategory,
ItemID,
Sales
FROM
MyTable
WHERE
CustomerID = 1
返回
ItemCategory | ItemID | Sales
A 0 75.00
A 1 50.00
A 2 0.00
B 3 25.00
B 4 25.00
C 5 20.00
C 6 30.00
C 7 10.00
C 8 0.00
C 9 50.00
如何修改此查询,以便收到按ItemCategory分组的每个项目的销售百分比?
也就是说,我希望这会回来:
ItemCategory | ItemID | Sales | PercentageOfCategory
A 0 75.00 60%
A 1 50.00 40%
A 2 0.00 0%
B 3 25.00 50%
B 4 25.00 50%
C 5 20.00 20%
C 6 30.00 30%
C 7 10.00 10%
C 8 0.00 0%
C 9 50.00 50%
我试图让这个例子尽可能简单,实际的查询非常复杂,但我想同样的逻辑仍然适用。
编辑:我相信服务器是sql server 2008
答案 0 :(得分:2)
你没有提到什么版本的SQL服务器,但如果你有2005+,那么你可以使用Common Table Expressions (CTE)
;WITH RawData As
(
SELECT
ItemCategory,
ItemID,
Sales
FROM
MyTable
WHERE
CustomerID = 1
),
GroupedData As
(
SELECT
ItemCategory,
Sum(Sales) As TotalSales
FROM
RawData
GROUP BY
ItemCategory
)
SELECT
R.ItemCategory,
R.ItemID,
R.Sales,
R.Sales / G.TotalSales * 100.0 As PercentageSales
FROM
RawData R
INNER JOIN
GroupedData G
ON
R.ItemCategory = G.ItemCategory
答案 1 :(得分:1)
假设CTE的SQL Server 2005+:
WITH cteCategoryTotals AS (
SELECT ItemCategory, SUM(Sales) AS TotalSales
FROM MyTable
WHERE CustomerID = 1
GROUP BY ItemCategory)
SELECT m.ItemCategory, m.ItemId, m.Sales, (m.Sales/c.TotalSales)*100.0 AS PercentageOfCategory
FROM MyTable m
INNER JOIN cteCategoryTotals
ON m.ItemCategory= c.ItemCategory
WHERE m.CustomerID = 1
答案 2 :(得分:0)
您可以使用SUM ... OVER
SELECT
ItemCategory,
ItemID,
Sales,
100.0 * Sales /
NULLIF(SUM(Sales) OVER (PARTITION BY ItemCategory),0) AS PercentageOfCategory
FROM
MyTable
WHERE
CustomerID = 1