How to merge 2 columns with all possible combinations in SQL?
Asked Answered
B

2

2

The question sounds confusing, but just look:

This way we can get the first column (col1):

select distinct maker
from product

And the second column (col2):

select distinct type,maker
from product

So now I need to get all possibly combinations from col1 and col2. Any suggestion?

Shortly, this:

A f1

B f2

Should become this:

A f1

A f2

B f1

B f2

P.S. This query won't return that I need.

select distinct A.maker, B.type
from product as A
Bollix answered 26/3, 2015 at 11:6 Comment(0)
S
7

Use cross join to get all combinations:

select m.maker, t.type
from (select distinct maker from product) m cross join
     (select distinct type from product) t;

This is ANSI SQL syntax and should be supported in any database.

Sherly answered 26/3, 2015 at 11:8 Comment(0)
M
1

variant using cross join but without subqueries will give same result as in @Gordon Linoff post, so you will get all possible combinations

select distinct A.maker, B.type
from product as A cross join product as B
Manhunt answered 23/4, 2015 at 11:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.