如果你使用SQL Server 2012或更高版本可以使用LAG()
和LEAD()
窗口函數來訪問一個和下一個行和使用查詢像下面來呈現你想要的結果:
-- 2012+ version
SELECT
ScheduledID, StartTime, EndTime, ModifiedTimeStamp,
CASE
WHEN prevts IS NULL THEN 'Schedule created'
WHEN prevStartTime <> StartTime AND prevEndTime = EndTime AND nextts IS NOT NULL
THEN CONCAT('Start Time Modified FROM ', prevStartTime, ' to ', StartTime)
WHEN prevStartTime <> StartTime AND prevEndTime <> EndTime AND nextts IS NOT NULL
THEN CONCAT('Start Time Modified FROM ', prevStartTime, ' to ', StartTime,
', End Time Modified FROM ', prevEndTime, ' to ', EndTime)
WHEN prevStartTime = StartTime AND prevEndTime <> EndTime AND nextts IS NOT NULL
THEN CONCAT('End Time Modified FROM ', prevEndTime, ' to ', EndTime)
WHEN nextts IS NULL
THEN 'Current Schedule'
END as 'Action Type'
FROM (
SELECT
ScheduledID,
prevStartTime = LAG(StartTime) OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp),
StartTime,
nextStartTime = LEAD(StartTime) OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp),
prevEndTime = LAG(EndTime) OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp),
EndTime,
nextEndTime = LEAD(EndTime) OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp),
prevts = LAG(ModifiedTimeStamp) OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp),
ModifiedTimeStamp,
nextts = LEAD(ModifiedTimeStamp) OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp)
FROM schedules
) a
如果您「再使用一個版本於2012年年紀較大,你可以使用ROW_NUMBER()
功能和自連接,而不是象下面這樣:
-- 2008 version
SELECT
curr.ScheduledID, curr.StartTime, curr.EndTime, curr.ModifiedTimeStamp,
CASE
WHEN prev.rn IS NULL THEN 'Schedule created'
WHEN prev.StartTime <> curr.StartTime AND prev.EndTime = curr.EndTime
THEN 'Start Time Modified FROM ' + prev.StartTime + ' to ' + curr.StartTime
WHEN prev.StartTime <> curr.StartTime AND prev.EndTime <> curr.EndTime AND next.rn IS NOT NULL
THEN 'Start Time Modified FROM ' + prev.StartTime + ' to ' + curr.StartTime
+ ', End Time Modified FROM ' + prev.EndTime + ' to ' + curr.EndTime
WHEN prev.EndTime <> curr.EndTime AND next.rn IS NOT NULL
THEN 'End Time Modified FROM ' + prev.EndTime + ' to ' + curr.EndTime
WHEN next.rn IS NULL THEN 'Current schedule'
END as 'Action Type'
FROM (
SELECT ScheduledID, StartTime, EndTime, ModifiedTimeStamp, ROW_NUMBER() OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp) rn
FROM schedules) curr
LEFT JOIN (
SELECT ScheduledID, StartTime, EndTime, ModifiedTimeStamp, ROW_NUMBER() OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp) rn
FROM schedules
) prev on curr.rn = prev.rn + 1 AND prev.ScheduledID = curr.ScheduledID
LEFT JOIN (
SELECT ScheduledID, StartTime, EndTime, ModifiedTimeStamp, ROW_NUMBER() OVER (PARTITION by ScheduledID ORDER BY ModifiedTimeStamp) rn
FROM schedules
) next on curr.rn = next.rn - 1 AND curr.ScheduledID = next.ScheduledID
ORDER BY curr.rn
Sample SQL Fiddle兩個版本。
哪個版本的SQL Server? – 2014-11-23 09:12:07
我正在使用SQL Server 2008版本。 – 2014-11-23 13:29:13