我有3个表格,我想退货 每个存款和信用金额的客户名称和总总和。
deposit customers credit
id id id
d_amount c_amount
customer_id name customer_id
type(credit,etc)
我是通过此查询=>
来完成的SELECT customers.name ,
sum(deposit.d_amount) as total_depot,
sum(credit.c_amount) as total_credit
from customers
inner join deposit on deposit.customer_id = customers.id
inner join credit on credit.customer_id = customers.id
and credit.type='credit'
group by customers.id order by customers.name asc
不幸的是, total_depot 和 total_credit 的结果不正确 但是当我单独这样做时,就像这样=>
SELECT customers.name , sum(deposit.d_amount) as total_depot
from customers
inner join deposit on deposit.customer_id = customers.id
group by customers.id order by customers.name asc
SELECT customers.name , sum(credit.d_amount) as total_credit
from customers
inner join credit on credit.customer_id = customers.id
and credit.type='credit'
group by customers.id order by customers.name asc
total_depot 和 total_credit 的结果是正确的 我不知道错误在哪里。
答案 0 :(得分:2)
第一个查询完全错误,JOINS会在结果中乘以行。一个客户的例子,他的3个学分和5个他的存款:
从客户中选择返回1行
客户INNER JOIN积分返回3行
客户INNER JOIN积分INNER JOIN存款返回15行
这不是你想要的。执行没有SUM和GROUP BY的查询,你会看到它。
这就是你想要的(简化,未经测试):
select customers.id, cr.amount, dep.amount
from customers
left join (select customer_id, sum(credit.d_amount) as amount from credits group by customer_id) cr on cr.customer_id=customers.id
left join (select customer_id, sum(deposits.d_amount) as amount from deposits group by customer_id) dep on dep.customer_id=customers.id
顺便说一句。当客户没有BOTH存款和信用时,需要左联接
答案 1 :(得分:0)
在加入表之前进行聚合:
select c.name, d.total_deposit, cr.total_credit
from customers c join
(select d.customer_id, sum(d.d_amount) as total_deposit
from deposit d
group by d.customer_id
) d
on d.customer_id = c.id join
(select c.customer_id, sum(c.c_amount) as total_credit
from credit c
where c.type = 'credit'
group by c.customer_id
) cr
on cr.customer_id = c.id
order by c.name asc;
答案 2 :(得分:0)
非常感谢每个人'
我尝试了所有这些考试,但它不起作用
我终于做到了这一点。 其工作。
select customers.name, total_depot , total_credit
from customers
left join (select customer_id , d_amount , sum(deposit.d_amount) as total_deposit from deposit group by customer_id) d on d.customers_id = customers.id
left join (select customer_id , c_amount , sum(credit.c_amount) as total_fact from credit where credit.type='credit' group by customer_id) c on c.id = customers.id
group by customers.name