简体   繁体   English

如何在SQL Server中选择后选择下一行?

[英]How to select next row after select in SQL Server?

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.我每次只需要选择value ='C'的行和下一行。

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 ).您使用ROW_NUMBER()为所有行提供序列号(请注意,您必须选择排序,我使用了Shift_Date )。 Then you take the rows with Shift2 = 'C' , then you UNION them with the rows that have a RN + 1然后用Shift2 = 'C'取行,然后将它们与具有RN + 1的行UNION起来

No SQL Fiddle today because (at least for me) it isn't working :-(今天没有 SQL Fiddle 因为(至少对我而言)它不起作用:-(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM