如何使一列表两列?

时间:2013-02-12 07:56:24

标签: sql tsql select

我希望从一列到两列创建一个表。例如,我有一个路径表。我有4行,我希望将它分成两列,就像在PATH2表中一样。我怎么能这样做?我希望这样做是为了计算每个路径值

╔══════╗
║ PATH ║
╠══════╣
║    1 ║
║    2 ║
║    3 ║
║    4 ║
╚══════╝

╔══════╦═══════╗
║ PATH ║ PATH2 ║
╠══════╬═══════╣
║    1 ║     2 ║
║    2 ║     3 ║
║    3 ║     4 ║
╚══════╩═══════╝

2 个答案:

答案 0 :(得分:4)

SQL Fiddle

MS SQL Server 2008架构设置

create table YourTable
(
  PATH int
)

insert into YourTable values (1),(2),(3),(4)

查询1

select T1.PATH,
       Lead.PATH as PATH2
from YourTable as T1
  cross apply (
              select top(1) PATH
              from YourTable as T2
              where T2.PATH > T1.PATH
              order by T2.PATH
              ) as Lead

<强> Results

| PATH | PATH2 |
----------------
|    1 |     2 |
|    2 |     3 |
|    3 |     4 |

答案 1 :(得分:3)

如果您正在使用SQL Server 2012,则可以使用LEAD分析功能。

WITH records
AS
(
    SELECT  PATH,
            LEAD(Path) OVER (ORDER BY PATH) Path2
    FROM    TableName
)
SELECT  Path, Path2
FROM    records 
WHERE   Path2 IS NOT NULL

或{如果在SQL SERVER 2005+

WITH records
AS
(
    SELECT  PATH,
            ROW_NUMBER() OVER (ORDER BY PATH) rn
    FROM    TableName
)
SELECT  a.Path, b.Path AS Path2
FROM    records a
        INNER JOIN records b
          ON a.rn+1 = b.rn