SQL表中的条件百分比列

时间:2019-11-20 12:51:39

标签: sql

我想添加一列,显示分数的百分比值,其中每条记录的分数除以其所属类别的分数总和。因此,新列中的值应为0.6、0.4、0.3和0.7

Id   Category   Score
1    foo        6        
2    foo        4          
3    bar        30
4    bar        70

我能想到的最好的办法是创建一个临时表,该表使用GROUP BY为Score创建总和值,然后将其联接到主表中。有更有效的方法吗?

2 个答案:

答案 0 :(得分:1)

使用窗口功能:

select t.*,
       score * 1.0 / sum(score) over (partition by category) as newcol
from t;

* 1.0是因为某些数据库执行整数除法。

答案 1 :(得分:1)

您也可以在不创建临时表的情况下进行操作。

SELECT A.* , CAST(Score*1.0/TotalScore AS DECIMAL(6,2))
FROM [table1] A 
JOIN (
        SELECT      Category
                    ,SUM(Score) TotalScore 
        FROM        [table1] 
        GROUP BY    Category
      ) B
ON    A.Category = B.Category