Tuesday, March 6, 2012

A Referense All Query

I have a table that contains a bunch of ID's and I am trying to write a query that will find every combination of id (order of t he ID's is not needed...IE: a,b is the same as b,a) but I cant seem to figure it out. Any help?

Here is my example:

Table

[ ID ]
[ a ]
[ b ]
[ c ]

Results

[ ID1 | ID2 ]
[ a | a ]
[ a | b ]
[ a | c ]
[ b | b ]
[ b | c ]

maybe this:

Code Snippet

create table #t (ID char(1))

insert into #t

select 'a'

union all select 'b'

union all select 'c'

;with cte as

(

select t1.id as id1, t2.id as id2, t1.cksum + t2.cksum as hash,

row_number() over(partition by t1.cksum + t2.cksum order by t1.id, t2.id) as rno

from

( select id, checksum(id) as cksum from #t) t1

full join ( select id, checksum(id) as cksum from #t) t2

on 1=1

)

select id1, id2

from cte

where rno = 1

No comments:

Post a Comment