将一列的备用行显示到另一列

时间:2013-04-01 05:24:59

标签: sql sql-server tsql

我有下表:

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 

但我不确定如何使用JOININNER JOIN功能。

3 个答案:

答案 0 :(得分:0)

如果您想使用LEAD()ROW_NUMBER(),则使用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)      ║
╚═══════════╩═════════════╩═══════════════╩═════════════╝

答案 1 :(得分: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

答案 2 :(得分:0)

此外,您可以使用带有APPLY子句

的OUTER 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上的演示