从没有重复记录的select中获取结果

时间:2017-09-05 18:56:53

标签: sql sql-server tsql select

我有记录表:

City Name     Seq

London           1
London           2
London           3
Madrid           4
London           5
Porto            6

问题是如何在字符串中获得结果(在没有重复记录的情况下合并所有内容)。

结果:伦敦 - 马德里 - 伦敦 - 波尔图

2 个答案:

答案 0 :(得分:2)

2012+ ... LAG()

的另一个选择

示例

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

答案 1 :(得分:0)

这个怎么样?

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