MySql中带有分组语句的两个不同表的总和之差

时间:2018-08-22 21:39:47

标签: mysql group-by

我正在创建一个带有销售/付款选项的客户的门户,其中所有销售都在一个表中,所有付款都在另一个表中。对于客户状态表,我需要获得每个客户的所有付款和每个客户的所有销售的总和加上它们之间的差额。

样本表:

clients

====================================
id  client_name
====================================
1   School "Mike Jordan"
2   Car wash "Blah blah"

purchasing

===================================
id  client_id  amount
===================================
1   1          1000
2   1          500
3   2          800
4   2          800

payments

===================================
id  client_id  amount
1   1          300
2   2          200
3   2          200

我尝试使用内部联接和分组,但这并不能正确地求和,总是大于一个,就像它在计数我不想要的东西(没有总数,只是试图求和:

select clients.`client_name `,
sum(purchasing.amount) as SOLD,
sum(payments.amount) as PAID 
from clients
inner join payments on payments.client_id=clients.id
inner join purchasing on purchasing.client_id=clients.id
group by clients.id

我得到的结果不同(都更大)。

client_name           SOLD  PAID
================================
School "Mike Jordan"  1500  600
Car wash "Blah blah"  3200  800

如果我尝试按Payments.id和/或purchase.id添加分组,则会得到两个以上的结果...我知道存在分组问题,但我真的不知道它在哪里。

我想添加新列,该列只是SOLD和PAID之间的区别,但是服务器会生成错误消息,提示SOLD和PAID不在字段列表中。

有什么主意如何通过单个查询完成此操作吗?

2 个答案:

答案 0 :(得分:2)

您可以尝试一下。使用UNION ALL合并purchasingpayments表,然后将join合并到clients

下一步执行SUMgroup by

create table clients(
   id int,
   client_name varchar(50)
);

insert into clients values (1,'School "Mike Jordan"');
insert into clients values (2,'Car wash "Blah blah"');


create table purchasing(
  id int,
   client_id int,
   amount int
);


insert into purchasing values (1,1,1000);
insert into purchasing values (2,1,500);
insert into purchasing values (3,2,800);
insert into purchasing values (4,2,800);

create table payments(
  id int,
   client_id int,
   amount int
);
insert into payments values (1,1,300);
insert into payments values (2,2,200);
insert into payments values (3,2,200);

查询1

select c.client_name,
       sum(SOLD) as SOLD,
        sum(PAID) as PAID
from (
    SELECT client_id,amount as SOLD,0 as PAID  
    FROM purchasing
    UNION ALL 
    SELECT client_id,0,amount   
    FROM payments
)t1 INNER JOIN clients c on t1.client_id = c.id
group by c.client_name

Results

|          client_name | SOLD | PAID |
|----------------------|------|------|
| Car wash "Blah blah" | 1600 |  400 |
| School "Mike Jordan" | 1500 |  300 |

答案 1 :(得分:0)

在进行联接之前,您需要汇总表。

SELECT clients.`client_name`
    ,purchasing_sum.SOLD
    ,payments_sum.PAID
FROM clients
INNER JOIN (
    SELECT client_id
        ,sum(amount) as PAID
    FROM payments
    GROUP BY client_id
    ) payments_sum ON payments_sum.client_id = clients.id
INNER JOIN (
    SELECT client_id
        ,sum(amount) as SOLD
    FROM purchasing
    GROUP BY client_id
    ) purchasing_sum ON purchasing_sum.client_id = clients.id
GROUP BY clients.id