2016-08-16 86 views
0

我有一個SQL數據庫,我基本上想要取一個組的平均值併除以總數的平均值。例如:用所有類別的平均值劃分類別的平均值

Fruit  Number_of_Seeds 
Rasp   50 
Rasp   65 
Straw   200 
Blue   20 
Straw   250 

所以我想形式的東西:

Fruit  Avg Seeds of Fruit/Avg of All Fruits 
Rasp     =((50+65)/2)/((50+65+200+20+250)/5)  
Straw 
Blue 

我已經有代碼來獲取果實平均種子,但如何將納入分母,如果我已經有一個通過Fruit聲明組?

希望這是有道理的。由於

+0

什麼dbms被使用? –

+0

SQL Server是dbms – user3697498

回答

1

一定要添加.0獲得精度和SELECT DISTINCT

Declare @YourTable table (Fruit varchar(50),Number_of_Seeds int) 
Insert into @YourTable values 
('Rasp',   50), 
('Rasp',   65), 
('Straw',   200), 
('Blue',   20), 
('Straw',   250) 

Select Distinct Fruit 
     ,AvgSeed= Avg(Number_of_Seeds+.0) over (Partition By Fruit)/Avg(Number_of_Seeds+.0) over() 
From @YourTable 

返回

Fruit AvgSeed 
Blue 0.170940 
Rasp 0.491452 
Straw 1.923076 
1
select fruit, avg(1.0*num_seeds)/(select avg(1.0*num_seeds) from tablename) 
from tablename 
group by fruit 

或使用窗函數

select fruit, avg(1.0*num_seeds) over(partition by fruit)/avg(1.0*num_seeds) over() 
from tablename