SQL-如何获取基于两个表的总和?

时间:2019-07-24 11:01:14

标签: mysql sql

所以我有两个表,一个是公司订单(order idcustomer namesum),另一个是债务(order id),其中包括没有已付款。我需要吸引最大的total debt客户。有些客户已下达1个以上的订单。最好的解决方案是什么?非常感谢你!

订单表:

CREATE TABLE orders( order_id INT PRIMARY KEY, name VARCHAR(30), sum INT );    
    INSERT INTO orders VALUES
    (1, 'Jack Smith', 123),
    (2, 'Mary Jane', 61),
    (3, 'John McCane', 90),
    (4, 'Jack Smith', 512),
    (5, 'Mary Jane', 33);

债务表:

CREATE TABLE debts( order_id INT PRIMARY KEY );
INSERT INTO debts VALUES 
(1),(4),(5);

现在我有这样的东西:

SELECT name,SUM(sum) FROM orders INNER JOIN debts ON orders.order_id = debts.order_id GROUP BY name;
+------------+----------+
| name       | SUM(sum) |
+------------+----------+
| Jack Smith |      635 |
| Mary Jane  |       33 |
+------------+----------+

所需结果如下:

name               sum
Jack Smith         635
Mary Jane          94
John McCane        90

3 个答案:

答案 0 :(得分:0)

select name,sum from orders o inner join debts d on o.order_id = d.order_id order by o.sum  desc 

将给您所有债务按降序排列的客户。如果您想让负债最高的客户添加limit 1

select name,sum from orders o inner join debts d on o.order_id = d.order_id order by o.sum  desc limit 1

答案 1 :(得分:0)

orders的ID中选择总和(总和)(从债务中选择order_id)

这可能对您有帮助

答案 2 :(得分:0)

这就是我想要的:

SELECT name,SUM(sum) FROM orders INNER JOIN debts ON orders.order_id = debts.order_id GROUP BY name;

谢谢大家的回答。