2017-03-17 161 views
0

列值的SQL計算百分比我有一個SQL查詢是這樣的:基於名稱

SELECT name, SUM(weight) weight, product FROM table GROUP BY name, product; 

這使我的輸出是這樣的:

|name   weight  product | 
    |custA  100  trash | 
    |custA  300  recycling| 
    |custB  50   trash | 
    |custB  450  recycling| 

現在我要計算的百分比基於名稱的重量,但仍然由產品分開。所以,而不是輸出看起來像這樣:

|name   weight  product | 
    |custA  .25  trash | 
    |custA  .75  recycling| 
    |custB  .10  trash | 
    |custB  .90  recycling| 

有沒有什麼辦法可以用普通的SQL查詢來完成這項工作?

回答

1

使用CTEcorrelated subquery

WITH TotalWeight(name, product, weightsum) AS 
(
    SELECT name, product, sum([weight]) as weightsum 
    FROM custdetails 
    GROUP BY name, product 
) 

SELECT name, product, weightsum, (0.0+weightsum)/(select sum([weight]) from custdetails where name = T.name) as percentage 
FROM TotalWeight T; 

此給出以下結果:

name product  weightsum percentage 
custA recycling 300  0.750000000000 
custA trash  100  0.250000000000 
custB recycling 450  0.900000000000 
custB trash  50  0.100000000000 
+0

很棒。謝謝。 –

0

嘗試這樣:

select a.name, a.weight/b.weight, a.product 
from (
    select name, sum(weight) as weight, product 
    from table 
    group by name, product 
) as a 
inner join (
    select name, sum(weight) as weight 
    from table 
    group by name 
) as b 
on (a.name = b.name) 
0

試試這個:

SELECT table.name, SUM(weight)/custWeightTable.custWeght as weight ,  product FROM table , (SELECT name, SUM (weight) as custWeight FROM table GROUP BY name) custWeightTable WHERE table.name = custWeightTable.name GROUP BY table.name, table.product; 
0

爲此,您可以使用窗口函數:

SELECT name, product, SUM(weight) as weight, 
     SUM(weight)/SUM(SUM(weight)) OVER (PARTITION BY name) as ratio 
FROM table 
GROUP BY name, product; 

注意,有些數據庫做整數除法。所以,如果體重是一個整數,你可能需要轉換爲某種類型的小數:

SELECT name, product, SUM(weight) as weight, 
     SUM(weight)/SUM(1.0*SUM(weight)) OVER (PARTITION BY name) as ratio 
FROM table 
GROUP BY name, product;