MYSQL从两个表计算金额?

时间:2014-04-14 19:54:40

标签: mysql sql jointable

我有2个mysql表:

"订单"表:

customer_id | money
3             120
5             80
3             45
3             70
6             20

"收集"表:

customer_id | money
3             50
3             70
4             20
4             90

我想要一个结果:

"总计"表:

customer_id | Amount
3             115
4             110
5             80
6             20
  1. "总计" table" customer_id"应该是单数的
  2. 金额=(SUM(所有客户orders.money) - SUM(所有客户collect.money))
  3. "钱"可以是NULL
  4. "订单" table可以有customer_id和"收集"表可能没有

    或者

    "收集" table可以有customer_id和" Orders"表可能没有

    如何为输出编写单个查询" Total"表

5 个答案:

答案 0 :(得分:3)

以下内容将返回您期望的结果。

SELECT 
customer_id,
SUM(amount) as amount
FROM (
  SELECT customer_id, SUM(money) as amount
  FROM orders GROUP BY customer_id

  UNION ALL

  SELECT customer_id, SUM(money) * -1 as amount
  FROM collecting GROUP BY customer_id
) as tb
GROUP BY customer_id;

customer_id = 4返回-110,而不是110,因为它只在收集表中。

示例:http://www.sqlfiddle.com/#!2/3b922/5/0

答案 1 :(得分:2)

最快的方法是将您的数据与collecting表中的货币值合并:

-- load test data
    create table orders(customer_id int, money int);
    insert into orders values
      (3,120),
      (5,80),
      (3,45),
      (3,70),
      (6,20);
    create table collecting(customer_id int,money int);
    insert into collecting values
      (3,50),
      (3,70),
      (4,20),
      (4,90);

-- populate Total table
    create table Total(customer_id int,Amount int);
    insert into Total
      select oc.customer_id,sum(oc.money) Amount
      from (
           select customer_id,coalesce(money,0) money from orders
           union all
           select customer_id,coalesce(-money,0) money from collecting
           ) oc
      group by oc.customer_id;

-- return results   
    select * from Total;

SQL小提琴:http://www.sqlfiddle.com/#!2/deebc

答案 2 :(得分:0)

您需要通过预先聚合数据来完成此操作。如果我认为orders首先出现,您可以使用left outer join

select o.customer_id, (o.money - coalesce(c.money)) as Amount
from (select o.customer_id, sum(o.money) as money
      from orders o
      group by o.customer_id
     ) o left outer join
     (select c.customer_id, sum(c.money) as money
      from collecting c
      group by c.customer_id
     ) c
     on o.customer_id = c.customer_id;

答案 3 :(得分:0)

这样的事情应该有效:

SELECT CASE 
        WHEN c.customer_id IS NULL
            THEN o.customer_id
        ELSE c.customer_id
        END
    ,sum(o.MONEY) - sum(c.MONEY)
FROM orders o
OUTER JOIN collecting c ON c.customer_id = o.customer_id
GROUP BY 1

答案 4 :(得分:0)

试试这个:

SELECT customer_id, SUM(o_money - c_money) AS Amount
FROM (
     SELECT customer_id, money AS o_money, 0 AS c_money FROM orders
     UNION ALL
     SELECT customer_id, 0 AS o_money, money AS c_money FROM collecting
     ) total
GROUP BY customer_id;

根据您的说明,您需要FULL [OUTER] JOIN,这是LEFT JOINRIGHT JOIN的组合。许多数据库不支持FULL JOIN,因此您需要使用UNION ALL来达到同样的效果。