如何在SQL Server中选择后选择下一行?
我有这个问题,我需要你的帮助:如何在SQL Server中选择后选择下一行?,sql,sql-server,Sql,Sql Server,我有这个问题,我需要你的帮助: 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
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
每次我只需要选择值为class='C'的行和下一行。查询可以写为:
; 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'获取行,然后将它们与具有RN+1的行合并
今天没有SQL Fiddle,因为至少对我来说它不起作用:-发布您在c或vb.net中尝试过的查询?我也看不到任何值字段,你是说移位2吗?读取要返回的行?下一行基于什么?