oracle从具有相同列

时间:2017-03-09 10:40:35

标签: sql oracle select database-design plsql

我有4个表,列有相似的列。

表1:

a1 b1 c1 timestamp1

表2:

a2 b2 c2 timestamp2

表3:

a3 b3 c3 timestamp3

表4:

a4 b4 c4 timestamp4

我需要的结果是,来自所有4个表的列(c1,c2,c3,c4)的最大值的时间戳值。

2 个答案:

答案 0 :(得分:1)

您可以使用SELECT a, b, c, timestamp FROM (SELECT a, b, c, timestmap, ROW_NUMBER() OVER (ORDER BY timestamp DESC) AS rn FROM (SELECT a1 AS a, b1 AS b, c1 AS c, timestamp FROM table1 UNION ALL SELECT a2 AS a, b2 AS b, c2 AS c, timestamp FROM table2 UNION ALL SELECT a3 AS a, b3 AS b, c3 AS c, timestamp FROM table3 UNION ALL SELECT a4 AS a, b4 AS b, c4 AS c, timestamp FROM table4)) WHERE rn = 1 模拟包含所有列的单个表,然后使用最大时间戳记行:

fetch first

或者,如果您使用的是Oracle 12c,则可以使用更优雅的SELECT a, b, c, timestamp FROM (SELECT a1 AS a, b1 AS b, c1 AS c, timestamp FROM table1 UNION ALL SELECT a2 AS a, b2 AS b, c2 AS c, timestamp FROM table2 UNION ALL SELECT a3 AS a, b3 AS b, c3 AS c, timestamp FROM table3 UNION ALL SELECT a4 AS a, b4 AS b, c4 AS c, timestamp FROM table4) ORDER BY timestamp DESC FETCH FIRST ROW ONLY 语法:

{{1}}

答案 1 :(得分:0)

如果您只需要每个表中C列的最大值。我们可以简单地在每个表上使用MAX functon然后使用union,再使用MAX来获得结果。希望这个也满足你的要求。

SELECT MAX(COL) FROM
(SELECT MAX(C1) COL FROM  TABLE1
UNION ALL
SELECT MAX(C2) FROM  TABLE2
UNION ALL
SELECT MAX(C3) FROM  TABLE3
UNION ALL
SELECT MAX(C4) FROM  TABLE4
);