2016-10-02 110 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