2016-08-25 32 views
0

Ich zog Daten aus einer Datenbank wie folgt (vereinfacht der Einfachheit halber), ich möchte eine Spalte namens "Prozentsatz" hinzufügen.Berechnen Prozent in SQL von Gruppe

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

danken Ihnen im Voraus

+0

Ist es MySQL oder SQL Server? –

Antwort

2

Der innere wählen Sie die garde Summe der id s bekommt.

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

Mit dem OVER (PARTITION BY), werden Sie nicht ein in SQL Server verbinden müssen

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

Ich habe wie Millionen Zeilen. Das wäre unmöglich, alle ihre Werte einzugeben. – Nayana

+0

Es sind Beispieldaten. Sie können einfach 'FROM your_table' (ersetzen Linie' 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