2016-10-02 24 views
-1

我在PostgreSQL中有一个带有3个字段的表:ebtyp,erdat,v_no。在PostgreSQL的Case语句中使用聚合和布尔值时遇到问题

输入:

enter image description here

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

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

输出:

enter image description here

我试过,但它不工作:

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语句?任何解决方案?

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-在那么当灰化-A-问题/ 285557#285557 –

回答

0

我觉得窗口函数应该提供你想要的功能。如果我理解正确的话,那么这将产生的问题的结果:

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; 
0

为了我您的需求理解你没有把理想的数据来呈现你的情况,所以我修改了它通过改变2 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