简体   繁体   English

SQL 表中的条件百分比列

[英]Conditional percentage column in SQL table

I want to add a column showing percentage values for Score, in which each record's score is divided by the sum of the scores for the category it's in. So the values in the new column should be 0.6, 0.4, 0.3 and 0.7.我想添加一个显示分数百分比值的列,其中每条记录的分数除以其所在类别的分数总和。因此,新列中的值应该是 0.6、0.4、0.3 和 0.7。

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

The best I can think to do is to create a temporary table that creates sum values for Score using GROUP BY and then JOIN-ing it to the main table.我能想到的最好的办法是创建一个临时表,使用 GROUP BY 为 Score 创建总和值,然后将其加入主表。 Is there a more efficient way of doing this?有没有更有效的方法来做到这一点?

Use window functions:使用 window 函数:

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

The * 1.0 is because some databases do integer division. * 1.0是因为有些数据库做integer划分。

You can also do it without creating temporary table.您也可以在不创建临时表的情况下执行此操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM