我有一个问题,我从两个表中选择如下:
select SUM(tc.WEEKLY_HOURS),
SUM(pc.var_cash)
from time_capture tc
LEFT OUTER JOIN PAYMENT_CAPTURE pc on tc.EMP_NO = pc.emp_no
AND tc.EFFECTIVE_DATE = pc.EFFECTIVE_DATE
where tc.effective_date = '17 June, 2012'
GROUP BY LEFT(tc.COST_CENTRE, 4)
这两个表包含:
time_capture
emp_no EFFECTIVE_DATE weekly_hours
---------- ----------------------- ----------------------
1234 2012-06-17 28
PAYMENT_CAPTURE
emp_no EFFECTIVE_DATE INPUT_CODE cost_centre var_cash
---------- ----------------------- ---------- ------------------------- ----------------------
1234 2012-06-17 KEY 5607.03 45
1234 2012-06-17 OTHER 5607.03 19.23
我期待sum(weekly_hours)
返回28,但它返回56(下方),因为(我认为)payment_capture
中的两行。
有人能指出我正确的方向吗?
非常感谢。
weekly_hours var_cash
---------------------- ----------------------
56 64.23
答案 0 :(得分:2)
您需要使用子查询预先汇总现金:
select
SUM(tc.WEEKLY_HOURS) as 'Hrs',
SUM(pc.var_cash) as 'Cash'
from
time_capture tc
LEFT OUTER JOIN
(
SELECT
Emp_No,
Effective_Date,
SUM(var_cash) as 'var_cash'
FROM
PAYMENT_CAPTURE)
pc
on tc.EMP_NO = pc.emp_no
AND tc.EFFECTIVE_DATE = pc.EFFECTIVE_DATE
where
tc.effective_date = '17 June, 2012'
GROUP BY L
EFT(tc.COST_CENTRE, 4)
答案 1 :(得分:1)
正在读它。由于您正在进行连接,因此返回:
1234 | 2012-06-07 | 28 | 1234 | 2012-06-07 | 5607.03 | 45
1234 | 2012-06-07 | 28 | 1234 | 2012-06-07 | 5607.03 | 19.23
因此,既然你在求和,你得到28 + 28 = 56,而45 + 19.23 = 64.23