mysql – SQL – 无法正确计算SUM

我一直在尝试这个SQL语句.

我有一个销售数据库,我需要做的就是:

SELECT 
  SUM(orders.total) as total, orders.transaction_date as date, 
  orders.id as orderid, orders.employee_id as empl 
from orders GROUP by orders.employee_id

这个查询很完美,它给了我所需要的一切.但是,我需要添加到目前为止已销售的数量,以便与此查询相对应:

SELECT order_id, SUM(quantity) 
FROM order_items 
Group By order_id

哪个也好.两者都很完美,但我需要将它们放入一个sql语句中.

当我尝试

SELECT 
  SUM(order_items.quantity), 
  SUM(orders.total) as total, 
  orders.transaction_date as date, 
  orders.id as orderid, 
  orders.employee_id as empl 
from 
  orders, order_items 
where 
  order_items.order_id = orders.id 
GROUP by 
  orders.employee_id

除了总数之外,一切似乎都是正确的.我不知道为什么会这样.

这是DB

命令:

id | employee_id | transaction_date | total

ORDER_ITEMS:

order_id | quantity

最佳答案 在将两个表连接在一起之前,需要单独聚合这两个表:

select sum(oi.quantity), sum(o.total) as total, 
       o.employee_id as empl 
from orders o join
     (select oi.order_id, sum(oi.quantity) as quantity 
      from order_items oi
      group by oi.order_id
     ) oi
     on oi.order_id = o.id 
group by o.employee_id;

在select中包含交易日期和订单ID没有意义.您按员工ID进行聚合,因此这些列可能(可能是)多个值.

点赞