Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Two Columns into One Distinct Ordered Column

Tags:

sql

sql-server

If I have a table like this:

Col 1 | Col 2
-------------
   A  |  1
   A  |  2
   B  |  1
   C  |  1
   C  |  2
   C  |  3

How can I write a query to pull one column that looks like this --

Col 1 
------
  A
  1
  2
  B
  1
  C
  1
  2
  3
like image 386
pizzaslice Avatar asked Jul 27 '26 22:07

pizzaslice


1 Answers

SELECT col1
FROM Some_Table_You_Did_Not_Name

UNION ALL

SELECT col2
FROM Some_Table_You_Did_Not_Name

If the order matters in your example then you want this:

WITH data AS
(
   SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY col1, col2) as RN
   FROM Some_Table_You_Did_Not_Name
)
SELECT col
FROM (
    SELECT DISTINCT col1 as col, RN, 1 as O
    FROM data

    UNION ALL

    SELECT DISTINCT col2 as col, RN, 2 as O
    FROM data
) JC_IS_THAT_GUY
ORDER BY RN ASC, O ASC, col ASC
like image 75
Hogan Avatar answered Jul 29 '26 11:07

Hogan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!