SQL:行不均匀的表的总和

时间:2016-05-26 08:35:23

标签: sql

我有这个sql语句:

SELECT
payment.receipt AS or_no,
payment.payment_dt,
payment.vno,
concat(p.family_name, ', ', p.given_name, ' ', p.middle_name, COALESCE(', ' || p.suffix, '')) AS name,
$$English's Special$$ AS department,
SUM(payment.amount) AS income,
SUM(discount.amount) AS discount,
0 AS other_discount,
0 AS tax
FROM payment_tbl payment
LEFT JOIN person p ON payment.person_id = p.id
INNER JOIN discount_tbl discount on payment.vno = discount.vno 
GROUP BY or_no, name, payment_dt, payment.vno, payment.amount

UNION ALL 

...


SELECT * FROM payment_tbl:
receipt | amount | vno
1       | 5000   | V2016197

SELECT * FROM discount_tbl;
id | vno       | gross | amount (20% discount)
1  | V2016197  | 0     | 0
2  | V2016197  | 0     | 0
3  | V2016197  | 3000  | 600

如果我执行select * from payment_tbl inner join discount_tbl,结果将是3行,因此SUM(payment.amount)将是15000而不是5000。

我如何加入这两个表?

3 个答案:

答案 0 :(得分:0)

select (select sum(amount) from payment_tbl a where a.vno = b.vno) as amount 
from discount_tbl b   

尝试此查询。而不是使用子查询来获取金额。

答案 1 :(得分:0)

我的建议?使用相关查询对discount_tbl中的金额求和,然后不会产生重复记录:

SELECT
payment.receipt AS or_no,
payment.payment_dt,
payment.vno,
concat(p.family_name, ', ', p.given_name, ' ', .middle_name, COALESCE(', ' || p.suffix, '')) AS name,
$$English's Special$$ AS department,
SUM(payment.amount) AS income,
(SELECT SUM(d.amount) FROM discount_tbl d
 WHERE d.vno = payment.vno) as discount ,
0 AS other_discount,
0 AS tax
FROM payment_tbl payment
LEFT JOIN person p ON payment.person_id = p.id
GROUP BY or_no, name, payment_dt, payment.vno, payment.amount

顺便说一下,CONCAT()你错过了.middle_name中的别名,错字?

答案 2 :(得分:0)

您应该在SUM表格上discount_tbl折扣并使用JOIN

中生成的表格
.
.
SUM(payment.amount) AS income,
discount.amount AS discount,
0 AS other_discount,
0 AS tax
FROM payment_tbl payment
LEFT JOIN person p ON payment.person_id = p.id
INNER JOIN ( SELECT vno,SUM(amount) amount FROM discount_tbl GROUP BY vno ) discount 
on payment.vno = discount.vno 
.
.