sql - How to get top 'n' percentage values -


col1    col2 b   5 b   10 b   20 b   30 b   200 b   300 

select top 50 percentage col2 mytable giving

col2 5 10 20 

whereas actual 50% different

col1 col2   total(of col2)   div(col2/total)    cumulativeaddition  % b   5           565                 0.01            0.01            1% b   10          565                 0.02            0.03            3% b   20          565                 0.04            0.06            6% b   30          565                 0.05            0.12            12% b   200         565                 0.35            0.47            47% b   300         565                 0.53            1.00            100% 

as can see

5   1% 10  3% 20  6% 30  12% 200 47% 

am using right sql function?

as mentioned, top syntax not want.

you require cumulative sum. alas, supported directed in sql server 2012, not in sql server 2008.

for readability, prefer using correlated subquery cumulative sum. rest of query arithmetic:

select col1, col2, totalcol2, cumsumcol2,        cumsumcol2 / cast(totalcol2 float) cumpercent (select col1, col2,              sum(col2) on (partition col1) totalcol2,              (select sum(col2) mytable t2 t2.col1 = t.col1 , t2.col2 <= t.col2              ) cumsumcol2       mytable t      ) t cumsumcol2 / cast(totalcol2 float) < 0.5 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -