我從這樣的數據庫中提取數據(爲簡單起見簡化),我想添加一個名爲「百分比」的列。按組計算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
. .
. .
. .
預先感謝您
我從這樣的數據庫中提取數據(爲簡單起見簡化),我想添加一個名爲「百分比」的列。按組計算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
. .
. .
. .
預先感謝您
內選擇獲取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
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
使用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)
我有像千禧行。不可能輸入所有的值。 – Nayana
這是示例數據。 您可以執行'FROM your_table'(將行'2'替換爲) –
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
它是MySQL或SQL服務器? –