我有这样的表格:
Products
ID | Name
1 | Prod1
2 | Prod2
Product_history
ID | Product_id | quantity | order_id | date
1 | 1 | 10 | 1 | 2014-01-01 10:00:00
2 | 1 | 11 | 1 | 2014-01-01 11:00:00
3 | 1 | 20 | 2 | 2014-01-01 09:00:00
4 | 2 | 50 | 2 | 2014-01-01 09:00:00
我无法创建查询女巫将只返回最后日期的每个订单数量总和的所有产品。在这个例子中,我想返回:
product_id | quantity
1 | 31 (11 + 20)
2 | 50
你能帮助我吗?
答案 0 :(得分:1)
select p1.product_id, sum(p1.quantity)
from product_history p1
join
(
select product_id, max(date) as date
from product_history
group by product_id
) p2 on p1.product_id = p2.product_id and p1.date = p2.date
group by p1.product_id
答案 1 :(得分:1)
以下是使用not exists
的方法:
select ph.product_id, sum(ph.quantity)
from product_history ph
where not exists (select 1
from product_history ph2
where ph2.order_id = ph.order_id and
ph2.product_id = ph.product_id and
ph2.date > ph.date
)
group by ph.product_id;
如果您的表很大,则需要product_history(order_id, product_id, date)
上的综合索引来提高性能。