频率分布与加权平均值

时间:2012-07-06 11:38:05

标签: sql sqlite

我的数据格式如下:

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

2 个答案:

答案 0 :(得分:4)

这可以为您提供所需的结果:

select type
    , cast(sum(amount) as decimal(10,5))/(select sum(amount) from t)
from t
group by type

请参阅Sql Fiddle for Demo

答案 1 :(得分:0)

这将工作

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