假设我有一个ID
列,其值为1,5,7。我可以使用什么SQL语句根据另一个值获取列中的下一个值。
示例:1之后的下一个值是5.
示例2:7之前的值是5
答案 0 :(得分:1)
没有任何窗函数或CTE:
select
t.id,
(select max(t1.id) from tbl t1 where t1.id < t.id) as previd,
(select min(t2.id) from tbl t2 where t2.id > t.id) as nextid
from tbl t
答案 1 :(得分:0)
在SQL Server的更高版本(2012+)中,有一些很好的Windowed函数可用于处理记录。但在2008年,这些都无法获得。相反,你可以使用OUTER APPLY。这将允许您使用主查询中的值过滤子查询。
WITH SampleValues AS
(
/* This CTE creates some sample values.
*/
SELECT
r.n
FROM
(
VALUES
(1),
(5),
(7)
) AS r(n)
)
SELECT
o.n,
prev.Previous_n,
[next].Next_n
FROM
SampleValues AS o
OUTER APPLY
(
-- Find the previou value by looking for the TOP 1 before the current.
SELECT TOP 1
o.n AS Original_n,
p.n AS Previous_n
FROM
SampleValues AS p
WHERE
p.n < o.n
ORDER BY
p.n DESC
) AS prev
OUTER APPLY
(
-- Find the next value by looking for the TOP 1 after the current.
SELECT TOP 1
n.n AS Original_n,
n.n AS Next_n
FROM
SampleValues AS n
WHERE
n.n > o.n
ORDER BY
n.n ASC
)AS [next]
;