tsql - t-sql group by category and get top n values -
imagine have table:
month | person | value ---------------------- jan   | p1     | 1 jan   | p2     | 2 jan   | p3     | 3 feb   | p1     | 5 feb   | p2     | 4 feb   | p3     | 3 feb   | p4     | 2 ... how can build t-sql query top 2 value rows , third sum of others?
something this:
result:  month | person | value ---------------------- jan   | p3     | 3 jan   | p2     | 2 jan   | others | 1 -(sum of bottom value - in case (jan, p1, 1)) feb   | p1     | 5 feb   | p2     | 4 feb   | others | 5 -(sum of bottom values - in case (feb, p3, 3) , (feb, p4, 2)) thanks
in assumption using sql server 2005 or higher, using cte trick.
- attach row_numbereach row, starting highest value, resetting each month.
- selecttop 2 rows each month query (rownumber <= 2)
- unionremaining rows (rownumber > 2)
sql statement
;with months (month, person, value) (   select 'jan', 'p1', 1 union   select 'jan', 'p2', 2 union   select 'jan', 'p3', 3 union   select 'feb', 'p1', 5 union   select 'feb', 'p2', 4 union   select 'feb', 'p3', 3 union   select 'feb', 'p4', 2 ), q (   select  month           , person           , value           , rownumber = row_number() on (partition month order value desc)      months ) select  month         , person         , value    (                   select  month                   , person                   , value                   , rownumber              q             rownumber <= 2            union           select  month                   , person = 'others'                   , sum(value)                   , max(rownumber)              q             rownumber > 2                   group                   month          ) q                           order         month desc         , rownumber kudo's go andriy teaching me new tricks.
Comments
Post a Comment