简体   繁体   中英

How to get all results from multiple columns in a single column - SQL?

I want to get all the results in 2 of my columns together.

I have a table my_table like:

colA    colB
a       e 
b       e 
c       f
d       g

Intended output:

id      letter
1       a       
2       b       
3       c       
4       d       
5       e 
6       f 
7       g

I know this is achievable with UNION but I'm a bit confused about how the numbering would work then. I'm good with a solution without UNION too. The order of letter in the output also doesn't matter, but each value needs a unique ID.

What I tried:

SELECT 
     row_number() OVER (ORDER BY letter) AS id,
     colA AS letter
FROM my_table
UNION
SELECT
     row_number() OVER (ORDER BY letter) AS id,
     colB AS letter
FROM my_table
SELECT row_number() OVER (ORDER BY letter) AS id, *
FROM (
     SELECT DISTINCT colA AS letter
     FROM my_table
     UNION
     SELECT DISTINCT colB AS letter
     FROM my_table
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM