Sql查询按用户ID分组的前两行

Sql查询按用户ID分组的前两行,sql,Sql,我有这样的数据 deviceId | userId | Time 20 | 1 | 2-Jan-18 21 | 1 | 2-Jan-19 22 | 1 | 2-Jan-10 30 | 2 | 2-Jan-18 30 | 2 | 2-Jan-19 我想查询用户使用的2个第一个设备,以及用户ID的时间组 userId|firstDeviceId|firstDeviceTime|second

我有这样的数据

deviceId | userId | Time
20       | 1      | 2-Jan-18
21       | 1      | 2-Jan-19
22       | 1      | 2-Jan-10
30       | 2      | 2-Jan-18
30       | 2      | 2-Jan-19
我想查询用户使用的2个第一个设备,以及用户ID的时间组

userId|firstDeviceId|firstDeviceTime|secondDeviceId|secondDeviceTime
1     |20           | 2-Jan-18      | 21           | 2-Jan-19
2     |30           | 2-Jan-18      | 30           | 2-Jan-19
你们能告诉我怎么做吗?感谢

典型方法使用行数和条件聚合:

select userid,
       max(case when seqnum = 1 then deviceid end) as deviceid_1,
       max(case when seqnum = 1 then devicetime end) as devicetime_1,
       max(case when seqnum = 2 then deviceid end) as deviceid_2,
       max(case when seqnum = 2 then devicetime end) as devicetime_2
from (select t.*, row_number() over (partition by userid order by device time desc) as seqnum
      from t
     ) t
where seqnum <= 2
group by userid;