2017-12-18 239 views
0

enter image description herePostgres的 - 從兩個表

的數據已經從具有一個至5月關係兩個表取出轉換行列。

查詢:

select temp1.code, temp1.name, temp_dt.item_type, 
    (select item_name from pr_payroll_item where xid = temp_dt.payroll_item_xid 
    ), 
    temp_dt.amount from pr_template temp1, pr_template_detail temp_dt 
    where temp1.xid = temp_dt.parent_xid; 
Item Type 
0 ear 
1 add 
2 ded 

我有我如何能做到這一點Postgres裏以這種方式與MH01 顯示數據

code name ear value  add value  ded value 
001  Nav  BASIC 1000.00 HR 600.00 PF 50.00 
       FUEL 200.00  
       Mobile 300.00 

同爲其他名稱爲 「我」?實現這個結果集的查詢應該是什麼。

回答

0

您的基本問題是您需要在一個案例中有效地彙總數據,然後顯示值之間的換行符,對吧?

你需要使用什麼是array_to_stringarray_agg,雖然在理論上,你在默認情況下需要一個ORDER BY子句將使用排順序,以便:

select temp1.code, temp1.name, temp_dt.item_type, 
(select item_name from pr_payroll_item where xid = temp_dt.payroll_item_xid 
), 
temp_dt.amount from pr_template temp1, pr_template_detail temp_dt 
where temp1.xid = temp_dt.parent_xid; 

變成(編輯做出加入更具可讀性等):

select temp1.code, temp1.name, 
     array_to_string(array_agg(temp_dt.item_type::text), E'\n') as eid, 
     array_to_string(array_agg(i.item_name), E'\n') as ear, 
     array_to_string(array_agg(temp_dt.amount::text)E'\n') as value 
    from pr_template_detail temp_dt 
    join pr_template temp1 on temp1.xid = temp_dt.parent_xid 
    join pr_payroll_item I on xid = temp_dt.payroll_item_xid 
group by temp1.code, temp1.name; 
+0

我不會說換行符。基本上我有一些記錄下的item_type 0(這成爲列1命名爲耳朵,我需要顯示的數額與列值相比)。同樣,我有記錄item_type 1命名爲添加我需要顯示值等等)。所以我顯示的結果集在1個主記錄下有6個子記錄。 –