我有这个问题,我需要你的帮助:
EmpNo Shift_Date Shift1 shift2 stamp_Date stamp_Time stamp_Type
426 2015-04-12 A 2015-04-12 10:09:00.000 I
426 2015-04-15 B C 2015-04-15 23:46:00.000 I
426 2015-04-15 B C 2015-04-15 23:45:00.000 O
426 2015-04-16 OF 2015-04-16 07:02:00.000 O
426 2015-04-17 A 2015-04-17 07:34:00.000 I
426 2015-04-18 A 2015-04-18 08:05:00.000 I
426 2015-04-19 A 2015-04-19 10:29:00.000 I
426 2015-04-24 A 2015-04-24 07:22:00.000 I
我只需要选择value ='C'
行,每次都选择下一行。
答案 0 :(得分:0)
查询可以写成:
; WITH Base AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY Shift_Date) RN FROM #Table1
)
, WithC AS (
SELECT * FROM Base WHERE Shift2 = 'C'
)
SELECT * FROM WithC
UNION
SELECT WithCNext.* FROM WithC C LEFT JOIN Base WithCNext ON C.RN + 1 = WithCNext.RN
您使用ROW_NUMBER()
为所有行提供序号(请注意,您必须选择排序,我使用了Shift_Date
)。然后,您使用Shift2 = 'C'
获取行,然后使用UNION
RN + 1
今天没有SQL小提琴,因为(至少对我来说)它不起作用: - (