SQL根据名称计算列值的百分比

时间:2017-03-17 22:22:21

标签: sql

我有一个SQL查询,如下所示:

data_scaled['sepal_width']

这给了我这样的输出:

    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|

有什么办法可以通过常规SQL查询来实现这个目的吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

答案 2 :(得分: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;

答案 3 :(得分: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;

请注意,某些数据库会执行整数除法。因此,如果weight是一个整数,您可能需要转换为某种类型的小数:

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;