1

我有下表:

Vehicle Id  Arrival Time    Position
4              20              200
4              10              100
4              30              300
4              40              400

我想像下面这样安排它:

Vehicle Id  Arrival Time    Start Position  End Position
4                10             100             200
4                20             200             300
4                30             300             400
4                40             400              --

我可以使用函数来解决问题,但是LEAD我想使用函数来解决它。ROW_NUMBER ()JOIN

我认为ROW_NUMBER ()功能将像:

SELECT
   *, 
   ROW_NUMBER () OVER (PARTITION BY Vehicle Id ORDER BY Vehicle Id, Arrival Time) AS RN 
FROM Table_name 

但我不确定我将如何使用JOINorINNER JOIN函数。

4

3 回答 3

0

您也可以将选项与 OUTER APPLY运算符与ORDER BY子句一起使用

SELECT t.VehicleId, t.ArrivalTime, 
       t.Position AS StartPosition, o.Position AS EndPosition
FROM dbo.test59 t OUTER APPLY (
                               SELECT TOP 1 Position
                               FROM dbo.test59 t2
                               WHERE t.VehicleId = t2.VehicleId
                                 AND t.ArrivalTime < t2.ArrivalTime
                               ORDER BY t2.ArrivalTime ASC
                               ) o
ORDER BY t.ArrivalTime

SQLFiddle上的演示

于 2013-04-01T06:59:01.520 回答
0

LEAD()如果您想使用ROW_NUMBER()and ,您仍然可以使用 using 获得相同的结果Common table Expression

WITH recordList
AS
(
    SELECT  VehicleId, ArrivalTime, Position,
            ROW_NUMBER() OVER (ORDER BY VehicleId, ArrivalTime) rn
    FROM    tableName
)
SELECT  a.VehicleId, 
        a.ArrivalTime, 
        a.Position StartPosition,
        b.Position EndPosition
FROM    recordList a
        LEFT JOIN recordList b
            ON a.rn + 1 = b.rn

输出

╔═══════════╦═════════════╦═══════════════╦═════════════╗
║ VEHICLEID ║ ARRIVALTIME ║ STARTPOSITION ║ ENDPOSITION ║
╠═══════════╬═════════════╬═══════════════╬═════════════╣
║         4 ║          10 ║           100 ║ 200         ║
║         4 ║          20 ║           200 ║ 300         ║
║         4 ║          30 ║           300 ║ 400         ║
║         4 ║          40 ║           400 ║ (null)      ║
╚═══════════╩═════════════╩═══════════════╩═════════════╝
于 2013-04-01T05:30:36.137 回答
0

请试试:

;WITH T as (
    select *, row_number() over (order by [Arrival Time]) RNum 
    from( 
        select 4 as [Vehicle Id], 20 [Arrival Time], 200 as Position union
        select 4 as [Vehicle Id], 10 [Arrival Time], 100 as Position union
        select 4 as [Vehicle Id], 30 [Arrival Time], 300 as Position union
        select 4 as [Vehicle Id], 40 [Arrival Time], 400 as Position
    )x
)
select 
    [Vehicle Id], 
    [Arrival Time], 
    Position as [Start Position], 
    (SELECT Position From T t2 WHERE t2.RNum=t1.Rnum+1)
from T t1
于 2013-04-01T05:33:16.520 回答