3

我希望将表格从一列变为两列。例如,我有一个路径表。我有 4 行,我希望像 PATH2 表中那样将其拆分为两列。我该怎么做?我希望这样做是为了计算每个路径值

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

进入

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

2 回答 2

4

SQL小提琴

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

结果

| PATH | PATH2 |
----------------
|    1 |     2 |
|    2 |     3 |
|    3 |     4 |
于 2013-02-12T08:08:25.103 回答
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
于 2013-02-12T08:02:19.130 回答