合并查询结果中的多个列的内容

Combine the content of multiple columns from the result of a query

我的问题是能够将包含相似数据的 2 列的内容与包含相似数据的其他两列的内容组合起来。问题是我想用相当长的查询结果来做,所以表没有保存来执行联合功能。

输入数据:

column a column b column c column d
a d g j
b e h k
c f i l

想要的结果:

column a column b
a d
b e
c f
g j
h k
i l

通用解决方案是 union all:

select a, b
from t
union all
select c, d
from t;

您可以使用 CTE 来表示:

with cte as (
      <subquery here>
     )
select a, b
from cte
union all
select c, d
from cte;

我不确定这会比 Gordon 的答案更容易实现,但另一种可能的方法如下:

WITH TwoRows AS
   (SELECT 1 as RowNo UNION SELECT 2 as RowNo)

SELECT
   CASE WHEN cte.RowNo = 1 THEN t.Column_A ELSE t.Column_C END AS Column_A
   CASE WHEN cte.RowNo = 1 THEN t.Column_B ELSE t.Column_D END AS Column_B
FROM
   TwoRows cte
   CROSS JOIN MyTable t