SQL unit value and cumulative sum by groups -
i'm still new sql , kind of stumped on one. appreciate or advice. have table value column , id column order value column in descending order. i.e:
value | id 12 | 09 | 08 | b 08 | c 07 | 06 | b 03 | b 01 | c
i trying 2 things:
- for each row, calculate percent of total sum respective id. row 1 12/(12+9+7), row 2: 3/(12+9+7), row 3: 8/(8+6+3), etc.
- calculate running total of percentage calculated in (1) each id. cumulative sum each id.
the output this.
value | id | unitvalue | runningtotal ------------------------------------- 12 | | 0.43 | 0.43 09 | | 0.32 | 0.75 08 | b | 0.47 | 0.47 08 | c | 0.89 | 0.89 07 | | 0.25 | 1.00 06 | b | 0.35 | 0.82 03 | b | 0.18 | 1.00 01 | c | 0.11 | 1.00
for sql server 2008
;with cte ( select value ,id ,convert(decimal(10,2),value/convert(decimal(10,2),sum(value) over(partition [id]))) [unit value] table1 ) select a.value,a.id,a.[unit value], (select sum(b.[unit value]) cte b a.id = b.id , b.[unit value] <= a.[unit value]) [runningtotal] cte order a.id,[runningtotal]
Comments
Post a Comment