获取最新版本更改时间戳SQL Server

时间:2017-08-04 22:56:25

标签: sql sql-server

我有以下记录集,我想获得上次版本更改的时间戳。

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

3 个答案:

答案 0 :(得分:0)

嗯。嗯。 。 。

select top (1) ver, min(date_create)
from t
group by ver
order by max(date_create) desc;

答案 1 :(得分:0)

WITH v_sorting AS
(SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) v_rnum
   FROM versions
),

v_tag AS
(SELECT v1.id, v1.ver, v1.date_create, CASE WHEN v1.ver <> v2.ver THEN 1 
ELSE 0 END tag
  FROM v_sorting v1, v_sorting v2
 WHERE v1.v_rnum = v2.v_rnum - 1
)

SELECT TOP(1) id, ver, date_create
  FROM v_tag
 WHERE tag = 1
 ORDER BY date_create DESC;

RESULT

id  ver     date_create
123 1.0.9.8 2016-03-12 13:38:44.950

答案 2 :(得分:0)

解决方案。获取每个版本的每个版本和最大日期。还要为每一行提供一个数字。接下来获取带有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