从三个表中选择并汇总数据

时间:2013-12-24 18:49:59

标签: mysql sql

我有三张桌子

客户

id | name
 1 | john

订单

id | customer_id | date
1  | 1           | 2013-01-01
2  | 1           | 2013-02-01
3  | 2           | 2013-03-01

ORDER_DETAILS

id | order_id  | qty | cost
1  | 1         | 2   | 10
2  | 1         | 5   | 10
3  | 2         | 2   | 10
4  | 2         | 2   | 15
5  | 3         | 3   | 15
6  | 3         | 3   | 15

我需要选择数据,以便我可以获得每个order_id的输出订单摘要 样本输出。我将使用特定的客户ID

查询数据库

输出

date       | amount | qty | order_id
2013-01-01 | 70     |  7  |  1
2013-02-01 | 50     |  4  |  2

这是我试过的

SELECT 
orders.id, orders.date, 
SUM(order_details.qty * order_details.cost) AS amount, 
SUM(order_details.qty) AS qty
FROM  orders 
LEFT OUTER JOIN order_details ON  order_details.order_id=orders.id AND orders.customer_id = 1 
GROUP BY orders.date

但是这会为所有客户返回相同的行,只是数量和成本没有值

3 个答案:

答案 0 :(得分:1)

也许

    SELECT 
orders.id, orders.date, 
SUM(order_details.qty * order_details.cost) AS amount, 
SUM(order_details.qty) AS qty
FROM  orders  
LEFT JOIN order_details ON  order_details.order_id=orders.id 
AND orders.customer_id = 1 
GROUP BY orders.date
HAVING amount is not null AND qty is not null

SQL Fiddle

答案 1 :(得分:1)

注意: 在以下查询中,假设日期作为OP中指定格式的字符串存储在数据库中。如果它们实际上存储为某种类型的日期和时间,那么您将需要修改此查询,以便从日期截断时间,以便日期代表整天。您可以使用 date date_format 功能。但是,您需要确保适当地修改查询,以便group by和select子句仍然有效。 我在查询中添加了此修改作为评论

select
  o.date  -- or date(o.date) as date
  , sum(odtc.total_cost) as amount
  , sum(odtc.qty) as qty
  , o.order_id
from
  orders o
  inner join (
    select
      od.id
      , od.order_id
      , od.qty
      , od.qty * od.cost as total_cost
    from
      order_details od
      inner join orders _o on _o.id = od.order_id
    where
      _o.customer_id = :customer_id
    group by
      od.id
      , od.order_id
      , od.qty
      , od.cost
  ) odtc on odtc.order_id = o.id
where
  o.customer_id = :customer_id
group by 
  o.date -- or date(o.date)
  , o.order_id
;

答案 2 :(得分:0)

我认为你不希望外连接只是一个简单的内连接在所有3个表上:

FROM orders, order_details, customer
WHERE orders.customer_id=customer.id
AND order_details.order_id=orders.id