我在SQL Server中有一个像这样的表:
Table1:
Id Symbol
1 a
5 c
8 d
3 b
我想要基于 Id
的排序数据,并在连续行中连接 symbol
:
Query Result:
Id Symbol
1 ab
3 bc
5 cd
8 d
这个结果的最佳查询是什么?
答案 0 :(得分:6)
在SQL Server 2012 +中:
SELECT
Id,
symbol + ISNULL(LEAD(symbol) OVER (ORDER BY Id), '') as symbole
FROM
t
或旧版本:
;WITH CTE AS (
SELECT
*, ROW_NUMBER() OVER (ORDER BY Id) AS rn
FROM
t)
SELECT t1.Id, t1.symbol + ISNULL(t2.symbol, '') As symbole
FROM CTE t1
LEFT JOIN CTE t2
ON t1.rn = t2.rn - 1
答案 1 :(得分:0)
使用Common Table Expression
。
按ID提供row_number订单。
<强>查询强>
;with cte as
(
select rn=row_number() over
(
order by id
),id,symbol
from table1
)
select t2.id,coalesce(t2.symbol+t1.symbol,t2.symbol) as symbol
from cte t1
right join cte t2
on t1.rn=t2.rn+1;