如何在sql server中找到以jumbled顺序用逗号分隔的重复值

时间:2016-02-23 21:41:10

标签: sql sql-server sql-server-2012

我在SQL Server 2012中有一个这样的表,其中一个列值用逗号分隔

field 1  field 2
1,2,3     a
4,5,6     b
3,2,1     c
2,3,1     d
6,5,4     e
7,5,9     f

如何编写查询以获取结果

field 1   field 2
1,2,3      a
3,2,1      c
2,3,1      d
4,5,6      b
6,5,4      e
7,5,9      f

任何人都可以帮忙请知道如何获得

1 个答案:

答案 0 :(得分:1)

首先,这是一个非常时髦的问题,因此解决方案也是完全狂暴的,所以不要批评,只是玩得开心......

首先你需要创建这个分割函数:

CREATE function [dbo].[f_split](@param nvarchar(max), @delimiter char(1))
returns @t table (val nvarchar(max), seq int) as
begin

set @param += @delimiter

;with a as
(
select cast(1 as bigint) f, charindex(@delimiter, @param) t, 1 seq
union all
select t + 1, charindex(@delimiter, @param, t + 1), seq + 1
from a
where charindex(@delimiter, @param, t + 1) > 0
)
insert @t
select substring(@param, f, t - f), seq from a
option (maxrecursion 0)
return
end

Parse comma-separated string to make IN List of strings in the Where clause提供

其次,拆分并订购临时表:

create table #a ([field 1] varchar (20), [field 2] varchar(20))
insert #a ([field 1], [field 2])
select '1,2,3','a' union all
select '4,5,6','b' union all
select '3,2,1','c' union all
select '2,3,1','d' union all
select '6,5,4','e' union all
select '7,5,9','f'

select a.[field 2],b.val
into #tt
    from #a a
        cross apply [dbo].[f_split] ([field 1],',') b
    order by 1,2

第三,以你想要的方式切片和切块:

SELECT [field 2],theCommaDelimitedVal, ROW_NUMBER () over ( partition by theCommaDelimitedVal order by [field 2])
FROM (
        select e.[field 2],
        stuff(
                (select ','+cast(i.val as varchar(1)) as [text()]
                from #tt i
                where i.[field 2] = e.[field 2]
                for xml path (''))
            ,1,1,'') as theCommaDelimitedVal 
        from #tt e
        group by e.[field 2]
    ) a
group by [field 2],theCommaDelimitedVal

我当然希望没有人认为我对所有这些严重的事情感到疯狂:)...至少它是非常非凡的