I am trying to find all the unique possible combinations of values in a column using SQL.
I have a table with a maximum of 5 values in a single column: something like:
a,
b,
c,
d,
e
I need help with a my SQL Server code to find only the UNIQUE combinations of the values which would be:
ab, ac, ad, ae, bc, bd, be, cd, ce, de, abc, acd, ade...
Currently I am using the below code to find the 1,2 value combinations. The table name is my_table
and the column with the values is non_unique_column
.
select
RANK() OVER (PARTITION BY '' ORDER BY concat(col1,col2,col3)) [index]
,* into final_comb_out
from (select
non_unique_column col1, NULL as col2,NULL AS COL3 FROM my_table
UNION ALL
SELECT DISTINCT LEAST(t1.non_unique_column, t2.non_unique_column) AS value1,
GREATEST(t1.non_unique_column, t2.non_unique_column) AS value2
,NULL AS value3
FROM my_table t1
CROSS JOIN my_table t2
WHERE t1.non_unique_column <> t2.non_unique_column
The issue with this code is that the LEAST and GREATEST function are not supported by the client system and cannot be included.
I would very much appreciate code that could help me out here. Thanks.
2条答案
按热度按时间mpbci0fu1#
You can use recursion:
Output:
Try it out here.
uubf1zoe2#
The fixed max length of the source table allows a plain join solution, e.g.
db<>fiddle
Still I'd prefer a recursive one as Sash Sinha suggested.