在 PostgreSQL 的 Case 语句中使用聚合和布尔值时遇到问题

Having trouble using aggregate and boolean in a Case Statement in PostgreSQL

我在 PostgreSQL 中有一个 table,其中包含 3 个字段:ebtyp、erdat、v_no。

输入:

我要申请:(case when ebtyp='LA' and erdat=max(erdat) then vbeln end) as Inbound_delivery_number

我不想过滤或使用 LA/AB 的 where 子句,因为我不想删除任何行。

输出:

我试过了但是没用:

select case 
        when ebtyp='LA' and erdat=max(erdat) 
             then v_no OVER (PARTITION BY ebtyp) 
      end as Inbound_delivery_number 
from abc.table1;

我们可以在 Case 语句中使用带布尔函数的聚合函数吗?有什么解决办法吗?

根据我对您的需求的理解,您没有提供理想的数据来展示您的情况,因此我通过将两个 erdat 更改为更高的数据来修改它:

 ebtyp |   erdat    | v_no
-------+------------+------
 LA    | 2016-09-09 |    4
 AB    | 2016-10-10 |    4
 LA    | 2016-11-11 |    5
 AB    | 2016-11-15 |    6

查询:

select 
  ebtyp, erdat, v_no, 
  max(case when ebtyp = 'LA' then erdat end) over () as max_erdat, 
  case when ebtyp = 'LA' then max(v_no) over (partition by ebtyp) else v_no end as max_v_no 
from abc.table1;

输出:

 ebtyp |   erdat    | v_no | max_erdat  | max_v_no
-------+------------+------+------------+----------
 AB    | 2016-10-10 |    4 | 2016-11-11 |        4
 AB    | 2016-11-15 |    6 | 2016-11-11 |        6
 LA    | 2016-09-09 |    4 | 2016-11-11 |        5
 LA    | 2016-11-11 |    5 | 2016-11-11 |        5

我认为 window 函数应该提供您想要的功能。如果我理解正确,那么这会产生问题中的结果:

select t1.*,
       max(erdate) over (partition by ebtype) as max_erdat,
       (case when ebtyp = 'LA'
             then max(v_no) over (partition by ebtyp) 
             else v_no
        end) as Inbound_delivery_number 
from abc.table1 t1;