【问题标题】:Get result from select without repeated records next to each other从选择中获取结果,没有相邻的重复记录
【发布时间】:2017-09-05 18:56:53
【问题描述】:

我有记录表:

City Name     Seq

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

问题是如何在字符串中得到结果(合并所有没有重复的记录)。

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

【问题讨论】:

  • 您还有更多数据用于测试目的吗?

标签: sql sql-server tsql select


【解决方案1】:

另一个选项如果 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

【讨论】:

    【解决方案2】:

    这个怎么样?

    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
    

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 2020-12-21
      相关资源
      最近更新 更多