2016-08-25 134 views
0

我從這樣的數據庫中提取數據(爲簡單起見簡化),我想添加一個名爲「百分比」的列。按組計算SQL中的百分比

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 
.  . 
.  . 
.  . 

預先感謝您

+0

它是MySQL或SQL服務器? –

回答

2

內選擇獲取garde總和id S的。

select t.id, t.grade, t.grade * 100/gsum 
from your_table t 
join 
(
    select id, sum(grade) as gsum 
    from your_table 
    group by id 
) tmp on tmp.id = t.id 
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 
1

使用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) 
+0

我有像千禧行。不可能輸入所有的值。 – Nayana

+0

這是示例數據。 您可以執行'FROM your_table'(將行'2'替換爲) –

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