有没有办法从SQL中的一列顺序选择值对?
即。如果我有一个包含一列数字的表
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
... ...
答案 0 :(得分: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
如果您不关心最后一行,那么您甚至可以单独使用CTE查询,而无需使用CTE。
答案 1 :(得分: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
答案 2 :(得分: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)
答案 3 :(得分: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
答案 4 :(得分: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