SQL Server Pivot加权平均值

时间:2019-12-04 02:43:55

标签: sql-server pivot

需要计算平均售价。

DECLARE @t TABLE (Item VARCHAR(50),Qty INT, Price REAL, [Month] VARCHAR(50))
INSERT INTO @t VALUES
('A',10 ,3,'JAN'),
('A',100,2,'JAN'),
('B',20 ,1,'JAN'),
('A',100,1,'FEB'),
('B',100,2,'FEB')

SELECT* FROM (SELECT Item, (Price*Qty) Price,[Month] FROM @t )t
PIVOT(SUM(Price) for [Month] in ([JAN],[FEB]))pvt

以上结果为

Item    JAN  FEB
A       230  100
B       20   200

我需要加权平均数。我需要的结果如下。

Item    JAN  FEB
A       2.09 1.00
B       1.00 2.00

项A Jan =(3 * 10 + 2 * 100)/(10 + 100)= 2.09

我使用SQL Server 2014

1 个答案:

答案 0 :(得分:0)

您需要在sum()之后再次pivot

SELECT * FROM 
(select Item, round(sum(Price*Qty*1.00) /sum(Qty * 1.00), 2) as price, [Month] FROM @t GROUP BY Item, [Month])t
PIVOT(SUM(Price) for [Month] in ([JAN],[FEB]))pvt

结果:

enter image description here

要使用小数格式:

SELECT Item, cast([JAN] as numeric(9,2)) as JAN, cast([FEB] as numeric(9,2)) as FEB  FROM 
(select Item, sum(Price*Qty) /sum(Qty) as Price, [Month] FROM @t GROUP BY Item, [Month])t
PIVOT(SUM(Price) for [Month] in ([JAN],[FEB]))pvt

结果:

enter image description here