表如下:
1) Categories: id, name
2) Countries: id, name
3) Producers: id, name, country_id
4) Products: id, name, price, category_id, producer_id
5) Customers: id, name, surname, age, country_id
6) Customer_orders: id, customer_id, product_id, quantity, discount, order_date
我想找到每个国家/地区最受欢迎的商品类别(最受欢迎的商品类别-产品是由指定国家/地区的生产商生产的)
我当前的方法
select countries.name, categories.name, sum(cs.quantity) from countries
join producers on producers.country_id = countries.id
join products on products.producer_id = producers.id
join categories on categories.id = products.category_id
join customerorders as cs on cs.product_id = products.id
group by countries.name
这实际上不是一个好的解决方案。不确定如何执行此操作,我想应该按国家/地区对所有产品进行分组,然后针对每个国家/地区对每种产品类别(指定国家/地区的生产商生产的产品)的产品数量进行计数,最后找到购买最多产品的类别。
答案 0 :(得分:2)
您需要修复group by
,然后使用窗口功能:
select c.*
from (select co.name as country_name, c.name as category_name, sum(co.quantity) as total_qty,
row_number() over (partition by co.name order by sum(co.quantity) desc) as seqnum
from countries co join
producers pr
on pr.country_id = co.id join
products p
on p.producer_id = pr.id join
categories c
on c.id = p.category_id join
customerorders co
on co.product_id = p.id
group by co.name, c.name
) c
where seqnum = 1;
这应该在MySQL 8+中有效。可以在早期版本中表达这一点,但是有点痛苦。