c1 c2
10 30
20 40
C1,C2 是两列,我希望使用 sql 查询得到如下所示的输出。
C3
10
20
30
40
使用UNION
(隐式不同)或UNION ALL
:
SELECT c1 AS c3 FROM tablename
UNION ALL
SELECT c2 FROM tablename
您可以使用UNION
, 没有ALL
关键字,查询的结果只是唯一值。如果要保留重复,请使用UNION ALL
.
SELECT C1 as C3 FROM TABLENAME
UNION
SELECT C2 as C3 FROM TABLENAME
您将需要使用UNION ALL
查询来获取结果:
select c1 as c3
from yourtable
union all
select c2 as c3
from yourtable
这种类型的查询会将数据从多列取消透视到多行。
根据您使用的数据库产品,有些产品具有UNPIVOT
为您进行数据转换的功能。例如,如果您使用 SQL Server 或 Oracle,则可以使用:
select c3
from yourtable
unpivot
(
c3 for col in (c1, c2)
) u
order by c3
这将保留按表排序
SELECT 1 AS ordering, c1 AS c3
FROM mytable
UNION
SELECT 2 AS ordering, c2 AS c3
FROM mytable
ORDER BY ordering, c3
如果你不能忽略排序列,你可以把它变成一个子查询
SELECT c3
FROM (
SELECT 1 AS ordering, c1 AS c3
FROM mytable
UNION
SELECT 2 AS ordering, c2 AS c3
FROM mytable) a
ORDER BY ordering, c3