first of all, this is an extremely funky problem, hence the solution is also totally berserk, so don't be critical and just have fun...
first you would need to create this split function:
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
courtesy of Parse comma-separated string to make IN List of strings in the Where clause
Second, split and order into temporary table:
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
Thirdly, slice and dice it whichever way you want:
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
and I certainly hope nobody thinks me crazy for taking all of this serious :)... at least it was rather extraordinary