2013-02-12 107 views
3

我想製作一列從一列到兩列。例如,我有一個路徑表。我有4行,我希望將它分成兩列,如PATH2表。我該怎麼做?我想這樣做是爲了計算每個路徑的價值如何製作一個列表兩列?

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

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

你一定要在某種基礎上分割它。那是什麼?你希望分裂的條件是什麼 – asifsid88 2013-02-12 07:57:21

+0

條件是前兩行(1,2)將在新表中的同一行中。第一個表中的第二行和第三行將在第二行在第二個表格中。它繼續像這樣..我希望找到路徑,並稍後分配到這些路徑.. – 2013-02-12 19:51:22

回答

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 | 
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 
+0

非常感謝您的答案。 – 2013-02-12 19:51:50

相關問題