c1 c2
10 30
20 40
C1,C2是两列,我希望使用sql查询输出如下所示。
C3
10
20
30
40
答案 0 :(得分:2)
使用UNION
(隐式不同)或UNION ALL
:
SELECT c1 AS c3 FROM tablename
UNION ALL
SELECT c2 FROM tablename
答案 1 :(得分:2)
您可以使用UNION
,不使用ALL
关键字,查询结果只是唯一值。如果您想保留重复内容,请使用UNION ALL
。
SELECT C1 as C3 FROM TABLENAME
UNION
SELECT C2 as C3 FROM TABLENAME
答案 2 :(得分:2)
您需要使用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
答案 3 :(得分:1)
这将按表
保留排序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