2017-07-25 48 views
1

我有一個表PostgreSQL的查詢,以獲得來自與同桌同桌的輸出值

id employee leave_days leave_type type 
1 ABC     10  sick remove 
2 ABC     20  sick add 
3 ABC     15  Annual remove 
4 ABC     50  Annual add 
5 XYZ     10  sick remove 
6 XYZ     20  sick add 
7 XYZ     15  Annual remove 
8 XYZ     50  Annual add 

從上面的表格,我將通過列名小組叫leave_type,然後我將合併行和輸出應該如下。

我必須按列名leave_type並添加一個名爲新列leave_allocated。在leave_allocated列中,列類型與值只會來。

id employee leave_days leave_type leave_allocated 
1 ABC    10   sick 20 
2 ABC    15  Annual 50 
3 XYZ    10   sick 20 
4 XYZ    15  Annual 50 

我試過用子查詢我無法匹配內部查詢與外部查詢。

+0

不能看到你的樣本數據和預期產出之間的差額。 –

+0

@SudiptaMondal呀錯誤typed..Thanks –

+0

標籤數據庫正確,肯定你不會使用3個數據庫來存儲信息離開呀 –

回答

2

這應該有助於

SELECT id, 
    employee, 
    leave_dates, 
    leave type, 
    (SELECT leave_days 
    FROM TABLE t2 
    WHERE t2.id = t1.id 
    AND t2.type = 'add' 
    ) leave_allocated 
FROM TABLE t1 
WHERE t1.type = 'remove' 
+0

...這是工作的罰款而不被列請假類型分組...謝謝... –

+0

選擇DISTINCT EMPLOYEE_ID,(選擇從hr_holidays T2 總和(number_of_days_temp)其中t2.employee_id = t1.employee_id和t2.type = '刪除' 和t2.holiday_status_id = t1.holiday_Status_id)截取, holiday_status_id, (SELECT SUM(number_of_days_temp )from hr_holidays t2 其中t2.employee_id = t1.employee_id和t2.type ='add' 和t2.holiday_status_id = t1.holiday_Status_id)從hr_holidays t1分配 其中t1.employee_id = 2 group by t1.id,t1.holiday_Status_id ...我嘗試了你的參考和它的作品...謝謝@Sudipta Mondal –