SQL Server Select Record based on datetime and user type -


     id|   type   |  datetime    |     ---| ---------|--------------|      1 | admin    | 2016-01-03   |      2 | user     | 2016-01-07   |      3 | user     | 2016-01-08   |      4 | admin    | 2016-01-04   |      5 | user     | 2016-01-01   |      6 | user     | 2016-01-03   |      7 | user     | 2016-01-05   |      8 | user     | 2016-01-09   | 

lets have table above , need rearrange based on datetime. first record must admin latest datetime among type of admin only. second fifth record must type of user sort datetime descending. again, sixth record must type of admin second latest datetime. expected result query shown in table below.

expected result:

     id|   type   |  datetime    |     ---| ---------|--------------|      4 | admin    | 2016-01-04   |      8 | user     | 2016-01-09   |      3 | user     | 2016-01-08   |              2 | user     | 2016-01-07   |      1 | admin    | 2016-01-03   |      7 | user     | 2016-01-05   |      6 | user     | 2016-01-03   |      5 | user     | 2016-01-01   | 

can guys give me idea on how write query expected result?

i found way without issues of ntile when count not divisible amount of users want group. based on gofr1's script, suggest use:

select  id,         [type],         [datetime] (     select  id,             [type],             [datetime],             row_number() on (order [datetime]) - 1 idx     yourtable     [type] = 'admin'     union     select  id,             [type],             [datetime],             floor((row_number() on (order [datetime]) - 1) / 3) idx     yourtable     [type] = 'user'     ) p order idx, [type] 

Comments

Popular posts from this blog

Lists in Python -

android - can not access to progress bar in an other activity -

java - Vaadin 7 Pass Data Between Views -