0
c1  c2

10  30
20  40

C1,C2 是两列,我希望使用 sql 查询得到如下所示的输出。

C3

10
20
30
40
4

4 回答 4

2

使用UNION(隐式不同)或UNION ALL

SELECT c1 AS c3 FROM tablename
UNION ALL
SELECT c2       FROM tablename
于 2013-03-19T14:26:08.907 回答
2

您可以使用UNION, 没有ALL关键字,查询的结果只是唯一值。如果要保留重复,请使用UNION ALL.

SELECT C1 as C3 FROM TABLENAME
UNION
SELECT C2 as C3 FROM TABLENAME
于 2013-03-19T14:26:28.623 回答
2

您将需要使用UNION ALL查询来获取结果:

select c1 as c3
from yourtable
union all
select c2 as c3
from yourtable

请参阅带有演示的 SQL Fiddle

这种类型的查询会将数据从多列取消透视到多行

根据您使用的数据库产品,有些产品具有UNPIVOT为您进行数据转换的功能。例如,如果您使用 SQL Server 或 Oracle,则可以使用:

select c3
from yourtable
unpivot
(
  c3 for col in (c1, c2)
) u
order by c3

请参阅带有演示的 SQL Fiddle

于 2013-03-19T14:26:35.080 回答
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
于 2013-03-19T14:27:07.937 回答