我是Oracle Sql的新手,并且对如何通过同一个表上的过滤器计算总金额进行了阻止。 e.g。
员工表
Emp_ID
Emp_name
交易档案
TR_ID (= Emp_ID )
TR_QTR
TR_Type
TR_Xref
TR_Amt
员工表
| 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 |
我想要一个select语句输出,并选择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 :(得分: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,否则为SUM 0.
答案 1 :(得分: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;
答案 2 :(得分: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