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

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -