SQL - 两列到一个不同的有序列

时间:2017-08-04 15:26:09

标签: sql sql-server

如果我有这样的表:

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

如何编写查询以拉出一个看起来像这样的列 -

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

3 个答案:

答案 0 :(得分:4)

SELECT col1
FROM Some_Table_You_Did_Not_Name

UNION ALL

SELECT col2
FROM Some_Table_You_Did_Not_Name

如果您的示例中的订单很重要,那么您需要:

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

答案 1 :(得分:3)

您可以使用如下查询:

SELECT Col1
FROM (
   SELECT DISTINCT Col1, Col1 AS Col2, 0 AS grp
   FROM mytable

   UNION ALL

   SELECT Col2 AS Col1, Col1 AS Col2, 1 AS grp
   FROM mytable) AS t
ORDER BY Col2, grp, Col1

Demo here

答案 2 :(得分:0)

绝对不需要做UNION,UNION ALL或多次引用表格来取消数据...

-- if Col2 is always a well ordered sequense like the test data...
SELECT 
    Col1 = x.Value
FROM 
    #TestData td
    CROSS APPLY ( VALUES (IIF(td.Col2 = 1, td.Col1, NULL)), (CAST(td.Col2 AS CHAR(1))) ) x (Value)
WHERE
    x.Value IS NOT NULL;

-- if it isn't...
WITH 
    cre_Add_RN AS (
        SELECT 
            td.Col1,
            td.Col2,
            RN = ROW_NUMBER() OVER (PARTITION BY td.Col1 ORDER BY td.Col2)
        FROM 
            #TestData td
        )
SELECT 
    x.Value
FROM 
    cre_Add_RN arn
    CROSS APPLY ( VALUES (IIF(arn.RN = 1, arn.Col1, NULL)), (CAST(arn.Col2 AS CHAR(1))) ) x (Value)
WHERE 
    x.Value IS NOT NULL;

HTH, 杰森