這個方法奏效,取決於數據和數據類型/模式(如果表的名稱是時間表):
SELECT DATE, time AS 'InTime(Mode-3)',
(SELECT TOP 1 time FROM timeTable
WHERE mode = 1
AND id = outerTable.id
AND date = outerTable.date
AND time > outerTable.time
ORDER BY date, time) AS 'OutTime(Mode-1)',
ID
FROM timeTable AS outerTable
WHERE mode = 3
- 的outerQuery只選擇在倍模式= 3
- 在innerQuery選擇下一個出時間,即correspondes到在時間選擇,並且僅返回第一。由於按日期和時間排序,它應該是下一個。 只有你給出的數據
測試
輸出:
Date | InTime(Mode-3) | OutTime(Mode-1) | ID
---------------|---------------------|---------------------|------
2017-01-01 | 13:00:00.0000000 | 14:00:00.0000000 | 10
2017-01-01 | 15:00:00.0000000 | 15:30:00.0000000 | 10
僅供參考:
我用這個表模式
CREATE TABLE timeTable(
date DATE,
time TIME,
mode INTEGER,
id INTEGER
);
更新:
隨着時間的推移 - 差:
SELECT *, DATEDIFF(MINUTE,INTIME,OUTTIME) AS [DIFFERENCE] FROM (
SELECT [DATE], [time] AS INTIME,
(SELECT TOP 1 [time] FROM timeTable
WHERE [mode] = 1
AND [id] = outerTable.id
AND [date] = outerTable.date
AND [time] > outerTable.time
ORDER BY [date], [time]) AS OUTTIME,
[ID]
FROM [timeTable] AS outerTable
WHERE [mode] = 3
) WholeData
你應該提供你正在尋找的結果和你已經嘗試任何企圖。 –
請閱讀[如何問一個好的SQL問題](http://meta.stackoverflow.com/questions/271055/tips-for-asking-a-good-structured-query-language-sql-question/271056)和[如何創建一個MCVE](http://stackoverflow.com/help/mcve) – Shnugo