with prod_mon_sales as ( select product_id, unit_price, month(order_date) as mon, sum(quantity*unit_price) as mon_total_sales, sum(quantity) as mon_total_quantity from orders join products using(product_id) where year(order_date) = 2023 group by product_id, month(order_date) ), rank_s as ( select product_id, if(customer_age <= 60, concat(round(customer_age, -1)-9, '-', round(customer_age, -1)), '61+') as customer_age_group, rank() over(partition by product_id order by sum(quantity) desc, customer_age) as rk from orders join customers using(customer_id) where year(order_date) = 2023 group by product_id, customer_id ), most_popular_cust as ( select product_id, customer_age_group from rank_s where rk=1 ) select product_id, sum(mon_total_sales) as total_sales, unit_price, round(sum(mon_total_quantity), 2) as total_quantity, round(sum(mon_total_sales)/12, 2) as avg_monthly_sales, round(max(mon_total_quantity), 2) as max_monthly_quantity, customer_age_group from prod_mon_sales join most_popular_cust using(product_id) group by product_id, customer_age_group order by total_sales desc, product_id
判断年龄范围那里其实还可以简化一下:
if(customer_age <= 60, concat(round(customer_age, -1)-9, '-', round(customer_age, -1)), '61+')



京公网安备 11010502036488号