我的源表中有这种类型的数据。
site date_time data
1016771 2016-06-04 00:00:00 LBV
1016771 2016-06-04 00:00:00 SOB
1016771 2016-06-04 01:29:00 LBV
1016771 2016-06-04 01:29:00 SOB
1016771 2016-06-04 05:51:00 SOB
1016771 2016-06-04 05:51:00 LBV
1016771 2016-06-04 08:35:00 SOB
1016771 2016-06-04 08:35:00 LBV
1016771 2016-06-04 11:18:00 LBV
1016771 2016-06-04 11:18:00 SOB
1016771 2016-06-04 12:20:00 LBV
1016771 2016-06-04 12:20:00 SOB
1016771 2016-06-04 13:24:00 LBV
1016771 2016-06-04 13:24:00 SOB
1016771 2016-06-04 14:04:00 LBV
1016771 2016-06-04 14:04:00 SOB
1016771 2016-06-04 15:27:00 LBV
1016773 2016-06-04 15:27:00 SOB
1016773 2016-06-04 16:55:00 LBV
1016773 2016-06-04 16:55:00 SOB
1016773 2016-06-04 18:15:00 LBV
1016773 2016-06-04 18:15:00 SOB
现在我想对这个数据模型执行一些操作。我想要在同一行中的下一行数据。 输出是这样的:
site SOB_date_time LBV_date_time
1016771 2016-06-04 00:00:00 2016-06-04 01:29:00
1016771 2016-06-04 05:51:00 2016-06-04 05:51:00
1016771 2016-06-04 08:35:00 2016-06-04 08:35:00
1016771 2016-06-04 11:18:00 2016-06-04 12:20:00
1016771 2016-06-04 12:20:00 2016-06-04 13:24:00
1016771 2016-06-04 13:24:00 2016-06-04 14:04:00
1016771 2016-06-04 14:04:00 2016-06-04 15:27:00
1016773 2016-06-04 15:27:00 2016-06-04 16:55:00
1016773 2016-06-04 16:55:00 2016-06-04 18:15:00
请你帮我解决这个问题。
答案 0 :(得分:2)
如果您只有2个不同的data
,则可以使用OUTER APPLY:
SELECT y.[site],
y.date_time as SOB_date_time,
t.date_time as LBV_date_time
FROM YourTable y
OUTER APPLY (
SELECT TOP 1 *
FROM YourTable
WHERE y.[site] = [site]
AND y.date_time < date_time
AND [data] = 'LBV'
ORDER BY date_time
) as t
WHERE y.[data] = 'SOB'
输出:
site SOB_date_time LBV_date_time
1016771 2016-06-04 00:00:00 2016-06-04 01:29:00
1016771 2016-06-04 01:29:00 2016-06-04 05:51:00
1016771 2016-06-04 05:51:00 2016-06-04 08:35:00
1016771 2016-06-04 08:35:00 2016-06-04 11:18:00
1016771 2016-06-04 11:18:00 2016-06-04 12:20:00
1016771 2016-06-04 12:20:00 2016-06-04 13:24:00
1016771 2016-06-04 13:24:00 2016-06-04 14:04:00
1016771 2016-06-04 14:04:00 2016-06-04 15:27:00
1016773 2016-06-04 15:27:00 2016-06-04 16:55:00
1016773 2016-06-04 16:55:00 2016-06-04 18:15:00
1016773 2016-06-04 18:15:00 NULL
TOP 1 WITH TIES和ROW_NUMBER()的另一种方式:
SELECT TOP 1 WITH TIES
y.[site],
y.date_time as SOB_date_time,
y1.date_time as LBV_date_time
FROM YourTable y
LEFT JOIN YourTable y1
ON y.[site] = y1.[site] and y1.[data] = 'LBV' AND y.date_time < y1.date_time
WHERE y.[data] = 'SOB'
ORDER BY ROW_NUMBER() OVER (PARTITION BY y.[site],y.date_time ORDER BY y1.date_time)