Sql 从select中获取结果,但不重复彼此相邻的记录
我有一张记录表:Sql 从select中获取结果,但不重复彼此相邻的记录,sql,sql-server,tsql,select,Sql,Sql Server,Tsql,Select,我有一张记录表: City Name Seq London 1 London 2 London 3 Madrid 4 London 5 Porto 6 问题是如何在没有重复记录的情况下,在字符串merge all中获得结果 结果:伦敦马德里伦敦波尔图这个怎么样 declare @table table (CityName varchar(64), seq int)
City Name Seq
London 1
London 2
London 3
Madrid 4
London 5
Porto 6
问题是如何在没有重复记录的情况下,在字符串merge all中获得结果
结果:伦敦马德里伦敦波尔图这个怎么样
declare @table table (CityName varchar(64), seq int)
insert into @table
values
('London',1),
('London',2),
('London',3),
('Madrid',4),
('London',5),
('Porto',6)
--find the next row that isn't the same city name (t2seq)
;with cte as(
select distinct
t.CityName
,t.seq
,min(t2.seq) as t2seq
from @table t
left join @table t2 on
t2.seq > t.seq
and t2.CityName <> t.CityName
group by
t.CityName
,t.seq),
--limit the result set to distinct list
cte2 as(
select distinct
CityName
,seq = isnull(t2seq,9999999)
from cte)
--use stuff to concat it together
select distinct
stuff(( select '-', + t2.CityName
from cte2 t2
order by seq
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from cte2
如果2012+,另一个选项。。。滞后 范例 返回
您是否有更多用于测试的数据?
Declare @YourTable Table ([City Name] varchar(50),[Seq] int)
Insert Into @YourTable Values
('London',1)
,('London',2)
,('London',3)
,('Madrid',4)
,('London',5)
,('Porto',6)
Select Stuff((Select '-' +Value From
(
Select top 1000 Value = case when [City Name]=lag([City Name],1) over (Order By Seq) then null else [City Name] end
From @YourTable
Order By Seq
) A
For XML Path ('')),1,1,'')
London-Madrid-London-Porto