我有带时间的Sql列。如果彼此相邻的两列之间的时间差大于1小时,我想输出它们
none
我的输出应该是这样
.box002
是否可以在Sql中编写这样的查询? 如果可能,我应该从SQL了解什么来执行该查询? (我知道SQL的基本水平,正在学习中)
谢谢。
答案 0 :(得分:3)
您可以像这样使用CTE和ROW_NUMBER
:
CREATE TABLE #Dates(DateColumn TIME)
INSERT INTO #Dates(DateColumn) VALUES
('04:05:44'),
('06:07:48'),
('08:15:44'),
('09:05:22'),
('11:15:27'),
('11:35:18'),
('12:16:54');*/
WITH CTE AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY DateColumn) AS RowNumb
FROM #Dates AS D
)
SELECT *
FROM CTE AS C
LEFT JOIN CTE AS C2 ON C.RowNumb = C2.RowNumb - 1
WHERE DATEDIFF(MINUTE, C.DateColumn, C2.DateColumn) >= 60
答案 1 :(得分:0)
对于MSSQL 2008,您可以使用answer provided by www.Studiosql.nl
下面的代码在MSSQL Server 2012中可以根据需要显示结果。
您可以为此使用LAG TSQL function。
CREATE TABLE #time (timeValue TIME)
INSERT INTO #time
values
('04:05:44'),
('06:07:48'),
('08:15:44'),
('09:05:22'),
('11:15:27'),
('11:35:18'),
('12:16:54');
SELECT temp.*
from
(SELECT timevalue, case when datediff(HH, lag(timevalue,1,timevalue) OVER(order by TIMEVALUE),timevalue) > 1 THEN CONCAT(lag(timevalue,1,timevalue) OVER(order by TIMEVALUE),' - ',timevalue) else null END AS displayvalue
FROM #time) as temp
where temp.displayValue is not null