postgresql如果其他字段为null,则选择最大值

时间:2018-04-16 09:49:00

标签: sql postgresql select aggregate-functions

我必须执行选择

select  field1, field2
from *table
where field1 not null and ( field2 in (4,5,6) or max(field2))

所以如果field2 = 4或5或6且field1不为null则ok 否则,如果field1为null,则取field2的最大值,其中field1不为null [max(field2)] ..

2 个答案:

答案 0 :(得分:0)

请尝试:

select  field1, field2
from * table
where case when field1 is not null then field2 in (4,5,6) else field2 in 
(select max(field2) field2 from table) end;

答案 1 :(得分:0)

您可以使用窗口函数:

select field1, field2
from (select t.*, max(field2) over () as max_field2
      from *table
     ) t
where field1 not null and (field2 in (4, 5, 6, max_field2));

也可以使用子查询/交叉连接:

select field1, field2
from *table t
where field1 is not null and
      (field2 in (4, 5, 6) or
       field2 = (select max(t2.field2) from *table2)
      );