选择值PostgreSQL之间的最大值

时间:2016-09-08 01:26:55

标签: sql postgresql

我想说我想在查询的两列之间选择max属性。它并不是整个表格的最大值。

类似的东西:

SELECT MAX(t1.c1, t2.c2)
FROM Table1 as t1, Table2 as t2
WHERE t1.id = t2.t1_id
AND ...... here goes more conditions.

我希望每一行都有映射值,表示t1.c1t2.c2之间的最大值

这可能吗?

2 个答案:

答案 0 :(得分:4)

使用greatest()

SELECT greatest(t1.c1, t2.c2)
FROM Table1 as t1
JOIN Table2 as t2 ON t1.id = t2.t1_id
-- WHERE ...... here goes more conditions

注意,我已将您的加入符号更改为更方便。

答案 1 :(得分:1)

使用union all

select max(c1)
from (select c1 from t1 union all select c2 from t2) t;

或者 - 可能更有效 - 使用greatest()

select greatest(c1, c2)
from (select max(c1) as c1 from t1) t1 cross join
     (select max(c2) as c2 from t2) t2;