我想从 3 个表中得到 2 个总和:
tbl_header
id id_quotation description
1 1 descr_1
2 2 descr_2
tbl_body
id id_quotation id_item item_cost
1 1 1 400
2 1 2 300
tbl_money
id id_quotation amount
1 1 200
2 1 300
3 2 100
所以我需要 1 个查询来从 tbl_head SUM(tbl_body.item_cost) WHERE tbl_body.id_quotation = 1
(在本例中为 400+300=700)和SUM(tbl_money.amount) WHERE id_quotation=1
(在本例中为 200+300=500)获取描述。Id_quotation
是所有表中的相同字段。
我用这个查询做到了:
select head.description,
sum(body.item_cost) as sum_1,
(select sum(money.amount)
from tbl_money money
where money.idquotation=head.idquotation
GROUP BY money.id_quotation) as sum_2
FROM tbl_body as body,
tbl_header as head
WHERE head.id_quotation=body.id_quotation
GROUP BY head.description
现在我想消除内部查询select sum(money.amount) from ...
并将其替换为类似SUM(money.amount)
但我总是得到记录 3 次所以总和是三倍大。不起作用的查询是:
SELECT head.description,
Sum(body.item_cost) AS sum_1,
sum(money.amount) as sum_2
FROM (tbl_header head
INNER JOIN tbl_body body
ON head.id_quotation=body.id_quotation)
INNER JOIN tbl_money money
ON head.id_quotation=money.id_quotation
WHERE head.id_person=1
AND money.id_quotation=body.id_quotation
GROUP BY head.description;
谢谢。