How do I return a list of all combinations of values in 2 columns so they are new rows in T-SQL?
e.g.
Col1, Col2
---- ----
1 2
1 4
1 5
<
I think this has been over complicated! Just:
SELECT distinct Col1, Col2
FROM MyTable
to get all possible combinations..
This uses 2 cte's, the first simply reproduces your input table, the second turns both columns into a single column. The final select crossjoin's this set to itself to produce the required output
with t(c1,c2)
AS
(
select 1,2
union select 1,4
union select 1,5
)
,t2(c)
as
(
select c1 from t
union select c2 from t
)
select t2_1.c, t2_2.c
from t2 t2_1
cross join t2 t2_2
where t2_1.c<t2_2.c
order by t2_1.c