2017-06-11 82 views
1

我是Oracle Sql的新手,並且在同一個表上的過濾器的總金額上有一個塊。例如來自同一個表的Oracle SQL - 2總計

EMPLOYEE表

Emp_ID 
Emp_name 

事務文件

TR_ID (= Emp_ID) 

TR_QTR 
TR_Type   
TR_Xref 
TR_Amt 

EMPLOYEE表

| EMP_ID | EMP_NAME  | 
+--------+----------------+ 
| 1  | sam spade  | 
| 2  | junior samples | 
| 3  | april showers | 

事務表

| ID | QTR | Type | Xref | Amt | 
+----+-----+------+------+-------+ 
| 1 | 1 | W | F | 5.00 | 
| 1 | 1 | W | T | 2.23 | 
| 1 | 2 | W | T | 5.55 | 
| 1 | 1 | W | T | 4.44 | 
| 1 | 1 | W | F | 3.25 | 
| 1 | 1 | G | B | 1.23 | 
| 2 | 1 | W | T | 6.10 | 
| 2 | 1 | G | Z | 12.12 | 
| 2 | 1 | W | F | 9.88 | 
| 2 | 1 | W | F | 8.70 | 
| 3 | 1 | W | F | 4.00 | 
| 3 | 1 | W | T | 3.00 | 
| 3 | 1 | W | T | 5.00 | 
| 3 | 2 | W | T | 7.00 | 

我想要一個查詢語句來輸出與所選TR_QTR = 1 我期待有一個用戶:

| ID | Name   | Total TR_Amt    | Total TR_AMT     | 
| |    |(TR_Type = W and TR_Xref = F)| (TR_Type = W and TR_Xref = T)| 
+----+---------------+-----------------------------+------------------------------+ 
| 1 |sam spade  | 8.25      |  6.67     | 
| 2 |junior samples | 18.58     |  6.10     | 
| 3 |april showers | 4.00      |  8.00     | 

難道我只是做了一個左邊的各金額的加入到同一個表兩次(事務文件)的我想總計?

任何幫助將有所值

+0

ID是交易表中員工ID的一個非常糟糕的名字。在一個事務表中,假設一個名爲ID的列是* transaction * ID,從而在表中標識一條記錄。如果是員工ID,則應該將其稱爲employee_id或類似名稱。 –

+0

這些不是實際的列名稱。謝謝你,先生。另外 - 謝謝你RLOG和謝謝你Nathan – DontKnow

回答

1

你想要的東西,如:

SELECT 
    e.Emp_ID 
, e.Emp_name 
, SUM(CASE WHEN t.TR_Type = 'W' AND t.TR_Xref = 'F') THEN TR_Amt ELSE 0 END) AS Total_W_F 
, SUM(CASE WHEN t.TR_Type = 'W' AND t.TR_Xref = 'T') THEN TR_Amt ELSE 0 END) AS Total_W_T 
FROM Employee_Table e 
LEFT OUTER JOIN Transaction_Table t ON e.Emp_ID = t.TR_ID 
WHERE t.TR_QTR = 1 
GROUP BY 
    e.Emp_ID 
, e.Emp_name 

基本上每一行你SUM TR_Amt當條件爲真,否則爲0 SUM

+0

選擇走這條路 - 所有的答案都非常感謝! – DontKnow

0

這應該這樣做。

WITH tr_wf AS (
SELECT tr_id as wfid, sum(tr_amt) as tr1 
    FROM transaction 
WHERE tr_type = 'W' AND tr_xref = 'F' 
GROUP BY tr_id 
), tr_wt AS (
SELECT tr_id as wtid, sum(tr_amt) as tr2 
    FROM transaction 
WHERE tr_type = 'W' AND trxref = 'T' 
GROUP BY tr_id 
) 
SELECT e.emp_id, e.emp_name, tr1 AS total_tr_amt_w_f, tr2 AS total_tr_amt_w_t 
    FROM employee e 
    JOIN tr_wf ON e.emp_id = wfid 
    JOIN tr_wt ON e.emp_id = wtid 
1

集團的交易通過員工ID和建設中的款項兩個XREF:

select 
    e.id, 
    e.name, 
    coalesce(t.sumf, 0) as total_f, 
    coalesce(t.sumt, 0) as total_t 
from employee e 
left join 
(
    select 
    id, 
    sum(case when xref = 'F' then amt end) as sumf, 
    sum(case when xref = 'T' then amt end) as sumt 
    from tr 
    where type = 'W' 
    and qtr = 1 
    group by id 
) t on t.id = e.id;