2016-04-18 72 views
0

有没有一种方法可以从SQL中的一列中按顺序选择值对?SQL Server - 从一列中选择值对

即如果我有一个表的数字

SomeID 
------ 
1 
2 
3 
5 
7 
11 

我需要像这样返回两列一组的一列:

FirstID SecondID 
------------------- 
1   2 
2   3 
3   5 
5   7 
7   11 

可以这样做?

编辑:

我已经提到,第一个结果集事项的顺序,可能不连续的。

即可能是

SomeID  
5 
3 
9 
8 
... 

FirstID SecondID 
5   3 
3   9 
9   8 
...  ... 
+1

任何ID /顺序列,我们可以用来获得“下一行”? – jarlh

+0

@jarlh目前,不......我开始意识到这可能是一个XY问题,因为我的单列结果集来自另一个查询,也许我可以把它工作到那里... – McFixit

回答

2
SELECT 
    t1.SomeID as FirstID, 
    t2.SomeID as SecondID 
FROM 
(
    SELECT SomeID, ROW_NUMBER()OVER(ORDER BY SomeID) as Inc 
    FROM TABLE 
) t1 
LEFT JOIN 
(
    SELECT SomeID, ROW_NUMBER()OVER(ORDER BY SomeID)-1 as Inc 
    FROM TABLE 
) t2 ON t2.Inc = t1.Inc 

作品SQL Server上> = 2005

+0

我将ROW_NUMBER工作到了原始(单列)结果集,这实际上就是我所用的 – McFixit

1

简单的方法,使用相关子查询返回以下值:

select t1.id as FirstID, (select min(t2.id) from tablename t2 
          where t2.id > t1.id) as SecondID 
from tablename 
where t1.id < (select max(id) from tablename) 
+0

你赢了3秒:) – Arvo

+0

@阿尔沃,也许我开始4秒之前? – jarlh

+0

@jarlh我应该提到,第一个查询的顺序很重要,可能不是连续的 – McFixit

2

您可以用窗口函数做到这一点,LEAD(或LAG

;WITH My_CTE AS 
(
SELECT 
    some_id as first_id, 
    LEAD(some_id, 1, NULL) OVER (ORDER BY some_id) AS second_id 
FROM 
    My_Table 
) 
SELECT 
    first_id, 
    second_id 
FROM 
    My_CTE 
WHERE 
    second_id IS NOT NULL -- to not get 11, NULL at the end 
ORDER BY 
    first_id 

如果你不关心如何得到最后一行t如果你不使用CTE,你可以直接使用CTE查询。

+1

不幸的是,我正在使用SQL Server 2008 R2和LEAD似乎已于2012年推出 – McFixit

1

简单只剩下表本身加入喜欢 -

Select a.somecol,b.somecol 
From TableA as a 
Left join TableA as b 
On b.someid = a.someid + 1 
Where b.someid is not null 
+0

并不总是+1。 (为什么左连接和b.someid不为空?) – jarlh

1

试试这个

declare @t table(SomeID int) insert into @t (SomeID) values 
(5),(3),(9),(8) 


;with t as(Select someid,row_number() over (order by (select 1)) as rn 
from @t)   
     Select a.someid,b.someid 
     From t as a 
     Left join t as b 
     On b.rn = a.rn + 1 
     Where b.someid is not null 
+0

为什么'left join'与'where b.someid是不是空'?你不能简单地做一个内部连接吗? – jarlh