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:

  1. 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.
  2. 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] 

sql fiddle demo


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -