我有以下格式的数据:
TYPE AMOUNT
Book £2
Pen £1
Book £3
我正在尝试将其输出为加权平均值:
TYPE Weighted Average
Book 0.833333333
Pen 0.166666667
到目前为止,我有:
Select TYPE, AMOUNT/SUM(AMOUNT)
FROM MyTable
Group by TYPE
这应该会给你你想要的结果:
select type
, cast(sum(amount) as decimal(10,5))/(select sum(amount) from t)
from t
group by type
这将起作用
DECLARE @Table1 TABLE (TYPE VARCHAR(10),AMOUNT FLOAT)
INSERT INTO @Table1 SELECT 'Book',2 UNION ALL SELECT 'Pen',1 UNION ALL SELECT 'Book',3
DECLARE @Total FLOAT
SELECT @Total=SUM(AMOUNT) FROM @Table1
SELECT TYPE,SUM(AMOUNT/@Total) FROM @Table1 GROUP BY TYPE