Skip to content
Advertisement

How to output every combination of values in 2 columns, in groups? – SQL

I have a table where I want every parent to be mapped to every child within each group.

Input:

Output:

So within each group, I want every value in parent to map to every value in child. If there are no values in child for a group, I want that group completely omitted (as shown where group_id = 3)

I was originally thinking of using GROUP BY 1, 2 and aggregating by something like MAX(child), but then I came across edge cases in my data where there may be >1 child. I also tried using CROSS JOIN but I’m struggling with getting my desired output. Thanks in advance.

Advertisement

Answer

Disclaimer, I don’t use Redshift so there may be better options. However, a CROSS JOIN should work. Just grab the DISTINCT parent values for all groups. Then do the same for the child values, and JOIN the two results together

Results:

group_id parent child
1 A E
1 B E
2 C F
2 D F
2 E F
2 C G
2 D G
2 E G

db<>fiddle here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement