gpt4 book ai didi

SQL Datediff - 查找行之间的 datediff

转载 作者:行者123 更新时间:2023-12-02 06:50:03 26 4
gpt4 key购买 nike

我想使用sql查询数据库以显示id 1,2,3等之间的时间差异。基本上它会比较其下面的行的所有记录。任何帮助,将不胜感激。

IDCODE  DATE TIME        DIFFERENCE (MINS)
1 02/03/2011 08:00 0
2 02/03/2011 08:10 10
3 02/03/2011 08:23 13
4 02/03/2011 08:25 2
5 02/03/2011 09:25 60
6 02/03/2011 10:20 55
7 02/03/2011 10:34 14

谢谢!

最佳答案

如果使用 SQL Server,一种方法是:

DECLARE @Data TABLE (IDCode INTEGER PRIMARY KEY, DateVal DATETIME)
INSERT @Data VALUES (1, '2011-03-02 08:00')
INSERT @Data VALUES (2, '2011-03-02 08:10')
INSERT @Data VALUES (3, '2011-03-02 08:23')
INSERT @Data VALUES (4, '2011-03-02 08:25')
INSERT @Data VALUES (5, '2011-03-02 09:25')
INSERT @Data VALUES (6, '2011-03-02 10:20')
INSERT @Data VALUES (7, '2011-03-02 10:34')

SELECT t1.IDCode, t1.DateVal, ISNULL(DATEDIFF(mi, x.DateVal, t1.DateVal), 0) AS Mins
FROM @Data t1
OUTER APPLY (
SELECT TOP 1 DateVal FROM @Data t2
WHERE t2.IDCode < t1.IDCode ORDER BY t2.IDCode DESC) x

另一种方法是使用 CTE 和 ROW_NUMBER(),如下所示:

;WITH CTE AS (SELECT ROW_NUMBER() OVER (ORDER BY IDCode) AS RowNo, IDCode, DateVal FROM @Data)

SELECT t1.IDCode, t1.DateVal, ISNULL(DATEDIFF(mi, t2.DateVal, t1.DateVal), 0) AS Mins
FROM CTE t1
LEFT JOIN CTE t2 ON t1.RowNo = t2.RowNo + 1
ORDER BY t1.IDCode

关于SQL Datediff - 查找行之间的 datediff,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5728602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com