I have this issue, I need your help:
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
I need to select only the rows with value ='C'
and the next row each time.
The query can be written as:
; 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
You use ROW_NUMBER()
to give a sequential number to all the rows (note that you have to select an ordering, I have used Shift_Date
). Then you take the rows with Shift2 = 'C'
, then you UNION
them with the rows that have a RN + 1
No SQL Fiddle today because (at least for me) it isn't working :-(
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.