如何限制每个设备的x最后几天结果的选择

时间:2018-06-07 22:00:19

标签: sql sql-server greatest-n-per-group

我想限制每个DeviceId&的x最后几天这个选择的ID:

SELECT DeviceId, Id, MAX(DateAndTime) as 'DateAndTime'
FROM EventAndMessage
GROUP BY DeviceId, Id
ORDER BY DateAndTime DESC`

结果示例:

DeviceId            Id      DateAndTime
00:11:22:33:44:55   00D330  2018-05-25 15:41:10.620
00:03:4F:00:10:94   027286  2018-05-11 09:23:26.927
00:03:4F:00:10:94   0351DE  2018-05-11 09:23:13.690
00:03:4F:00:10:94   0351DE  2018-05-11 09:23:09.747
00:03:4F:00:10:94   0351DE  2018-05-11 09:23:01.797
00:03:4F:00:10:94   0351C4  2018-05-11 09:22:47.633

在这个例子中,我想限制2个最年轻的记录。 注意:2应该是我可以更改的参数。

然后应该是正确的结果:

DeviceId            Id      DateAndTime
00:11:22:33:44:55   00D330  2018-05-25 15:41:10.620
00:03:4F:00:10:94   027286  2018-05-11 09:23:26.927
00:03:4F:00:10:94   0351DE  2018-05-11 09:23:13.690
00:03:4F:00:10:94   0351DE  2018-05-11 09:23:09.747
00:03:4F:00:10:94   0351C4  2018-05-11 09:22:47.633

由于

1 个答案:

答案 0 :(得分:0)

Oracle 12c及更高版本 -

SELECT DeviceId, Id, MAX(DateAndTime) as 'DateAndTime'
FROM EventAndMessage
GROUP BY DeviceId, Id
ORDER BY DateAndTime DESC
FETCH FIRST X ROWS ONLY;