按组计算SQL中的PERCENTAGE

时间:2016-08-25 01:07:08

标签: mysql sql sql-server

我从这样的数据库中提取数据(为简单起见而简化),我想添加一个名为“百分比”的列。

ID   GRADE   PERCENTAGE
 1     10        10/(10+20) * 100 -- THIS PART SHOULD BE SHOWN IN DIGIT
 1     20           .
 2     15           15/(15+24+16) * 100
 2     24
 2     16
 3     29
 4     96
 4     159
 .     .
 .     .
 .     .

提前谢谢

4 个答案:

答案 0 :(得分:2)

内部选择获得garde的{​​{1}}总和。

id

答案 1 :(得分:2)

使用OVER(PARTITION BY),您不需要在SQL Server中加入

SELECT *,  100*Grade/ SUM(Grade) OVER(PARTITION BY ID) AS Percentage
FROM (
     VALUES(1, 10),(1,20), (2, 15), (2,24), (2,16), (3,29)
) your_table (ID, GRADE)

答案 2 :(得分:0)

SELECT t1.ID,
       t1.GRADE,
       100.0 * (t1.GRADE / t2.gradeSum) AS PERCENTAGE   -- important: multiply
FROM yourTable t1                                       -- by 100.0 here
INNER JOIN
(
    SELECT ID, SUM(GRADE) AS gradeSum
    FROM yourTable
    GROUP BY ID
) t2

答案 3 :(得分:0)

select
a.id, a.grade
, case
    when b.total = 0 then 0
    else a.grade/b.grade * 100
  end as percentage
from
data a
cross apply (
   select sum(tot.grade) as total
   from data tot where a.id = tot.id
) b