2016-11-04 29 views
1

我有一組PostgreSQL的數據,這看起來像一個所附照片(PIC1-樣本數據):無法找出確切的PostgreSQL的查詢

Pic 1-Sample Data

custom_field列將確定是否行條目是「部門ID」還是「高優先級角色?」 text_value列的前六位數字將給出部門代碼。 正如您所看到的,無論custom_field是「高優先級角色?」,text_value列中的值都是'是'。 現在我的要求是隻提取那些custom_field是'高優先級角色'的記錄。這聽起來很簡單,但它也應該有「部門ID」附加到它。

注意:job_id不是唯一的。每個job_id對應'高優先級角色?'也會有一個重複的條目,其中custom_field中的值爲'Department ID'(請參閱附圖2以供參考)。

Pic 2

+0

http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-碼上那麼當灰化-A-問題/ 285557#285557 –

回答

0

像這樣的事情?

select 
    a.*, 
    b.display_value as department 
from (
    select 
     * 
    from 
     <table> 
    where 
     custom_field = 'High Priority Role?' 
) a 
inner join 
    <table> b 
on 
    a.job_id = b.job_id 
where 
    b.custom_field != 'High Priority Role?' 
group by 
    a.job_id, 
    a.custom_field, 
    a.float_value, 
    a.date_value, 
    a.display_value, 
    a.text_value, 
    a.unit, 
    b.display_value 

我在MariaDB中測試過,不是PostgreSQL,但它應該可以工作。

http://sqlfiddle.com/#!15/62ca4/3/0

0

這是一個簡單join

select t.*, left(t2.text_value, 6) as department_id 
from t join 
    t t2 
    on t.job_id = t2.job_id and 
     t.custom_field = 'High Priority Role?' and 
     t2.custom_field <> 'High Priority Role?'; 

這假定有一個與部門ID只有一個匹配的工作。

如果有多個,然後去一個橫向聯接:

select t.*, left(t2.text_value, 6) as department_id 
from t, lateral 
    (select t2.* 
     from t t2 
     where t.job_id = t2.job_id and 
      t.custom_field = 'High Priority Role?' and 
      t2.custom_field <> 'High Priority Role?' 
     fetch first 1 row only -- no `order by` because any match will do 
    ) t2;