其實是可以做到的,
概念是用分組排序,來找出與自己日期相差最少的,即是自己的"下一筆"。
手邊沒有MSSQL,憑空寫不確定有沒有錯,請試試看:
SELECT Date1 [Date], Orders, daydiff NextDataDayDiff
FROM
(
SELECT Date1, Orders, daydiff
, Row_Number() OVER (PARTITION BY Date1 ORDER BY daydiff) RW
FROM
(
SELECT t1.Date Date1, t2.Date Date2, t1.Orders
, datediff(day,t1.Date ,t2.Date) AS daydiff
FROM @Temp t1 with(nolock)
LEFT JOIN @Temp t2 with(nolock)
ON t1.Date<t2.Date
) temp
) temp
WHERE RW=1
※ 引述《Severine (賽非茵)》之銘言:
: DB: MS SQL
: 估狗了很久 剛剛也在本版搜尋了一下類似問題 找不太到..
: 只好發文問一下!
: 我想要取得每筆紀錄的時間間隔 請問該怎麼做呢?
: =========================================================
: 問完以後改寫了一個blueshop的範例
: DECLARE @Temp table (Date datetime, Orders int)
: INSERT INTO @Temp VALUES ('2012/2/1',1000)
: INSERT INTO @Temp VALUES ('2012/2/2',800)
: INSERT INTO @Temp VALUES ('2012/2/3',3500)
: INSERT INTO @Temp VALUES ('2012/2/4',4000)
: SELECT
: T1.Date ,
: ISNULL(datediff(day,T2.Date ,T1.Date),null) AS daydiff
: FROM @Temp AS T1
: LEFT JOIN @Temp AS T2 ON T1.Date = DATEADD(d,1,T2.Date)
: ===============以上可以算出後四筆的相差時間==============
: 但是以下就不行,想必是對left join用法的理解錯誤
: DECLARE @Temp table (Date datetime, Orders int)
: INSERT INTO @Temp VALUES ('2012/2/1',1000)
: INSERT INTO @Temp VALUES ('2012/2/12',800) <=修改過
: INSERT INTO @Temp VALUES ('2012/2/13',3500) <=
: INSERT INTO @Temp VALUES ('2012/2/24',4000) <=
: SELECT
: T1.Date ,
: ISNULL(datediff(day,T2.Date ,T1.Date),null) AS daydiff
: FROM @Temp AS T1
: LEFT JOIN @Temp AS T2 ON T1.Date = DATEADD(d,1,T2.Date)
: ========================================================
: 請問該如何修改呢? 謝謝 ><