我有以下记录集,我想获取上次版本更改的时间戳。
id ver date_create
123 1.0.9.8 2016-04-07 12:36:26.567
123 1.0.9.8 2016-03-25 09:10:26.303
123 1.0.9.8 2016-03-25 08:50:42.553
123 1.0.9.8 2016-03-24 11:09:47.620
123 1.0.9.8 2016-03-12 21:30:47.823
123 1.0.9.8 2016-03-12 13:38:44.950 <-- I have to get this record only
123 1.0.0.4 2016-03-06 20:26:54.477
123 1.0.9.8 2016-03-06 16:25:28.790
123 1.0.0.4 2016-03-03 21:41:35.807
123 1.0.0.4 2016-03-02 19:00:30.257
123 1.0.9.8 2016-03-02 18:24:42.060
123 1.0.0.4 2016-02-29 08:04:43.367
我有以下查询,我可以获得最大版本,然后是滞后。但是我不知道如何获得最小(时间戳)
SELECT id,ver,date_create,LAG(date_create) OVER (ORDER BY date_create DESC) AS lag
FROM mytable
ORDER BY date_create DESC
输出
123 1.0.9.8 2016-05-10 07:13:55.070 NULL
123 1.0.0.4 2016-03-06 20:26:54.477 2016-03-12 13:38:44.950 <-- I got the timestamp using the lag
期望输出
123 1.0.9.8 2016-03-12 13:38:44.950
解决方案。获取每个版本的每个版本和最大日期。还给每一行一个数字。接下来获取具有最大日期的版本,row_no=2,并获取该版本以上的所有行,最后获取最小日期。
;WITH meter_versions AS
(
SELECT id, ver, date_create = MAX(date_create), row_no = ROW_NUMBER() OVER (PARTITION BY id ORDER BY MAX(date_create) DESC)
FROM mytable
GROUP BY id, ver
)
SELECT a.id,a.ver, date_create = MIN(a.date_create)
FROM meter_versions
JOIN mytable a
ON a.id = meter_versions.id
AND a.date_create > meter_versions.date_create
WHERE meter_versions.row_no = 2
GROUP BY a.id,a.ver
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句