首页 > 解决方案 > 使用 MySQL 查找基于国家/地区的销售统计数据

问题描述

这是我的数据集

在此处输入图像描述

在这里,我需要找到摩托车在国家/地区的销售额以及 2018 年的收入。收入按数量 * 价格计算。这就是输出的样子。

在此处输入图像描述

这是我在 mysql 中编写的查询。

select con.name as country_name
      , mo.name as motor_cycle_model
      , sum(sa.quantity*mo.price) as revenue

from sales sa
    left join country con on (con.id=sa.country_id)
    left join motorcycle_model mo on (mo.id=sa.model_id)
 where year(sales_date) = '2018'
 group by 1,2
 order by 1

但这里的问题是我无法获得 2018 年没有销售的国家/地区。

标签: mysql

解决方案


尝试:

select con.name as country_name
      , mo.name as motor_cycle_model
      , sum(sa.quantity*mo.price) as revenue

from country con
    left join sales sa on (con.id=sa.country_id)
    left join motorcycle_model mo on (mo.id=sa.model_id)
 where year(sales_date) = '2018'
 group by 1,2
 order by 1

编辑:因为正如@Strawberry 所评论的,上面是一个inner join

上面是inner join因为,在执行 a 时,left join您不应该对要加入的表中的字段进行过滤。

在这种情况下,对 进行了左连接sales,之后由于where yea(sales_date)=2018. 这会导致所有国家都被排除在没有销售的结果之外。

更正的语句 dbfiddle

首先我们选择stock(因为我有它的名字),然后对sales2018 年进行左连接。

select 
    stock.country_name
    , stock.motor_cycle_model
    , sum(COALESCE(sa.quantity * stock.price,0)) as revenue
from    
   (select con.id as cid
      , con.name as country_name
      , mo.id as mid
      , mo.name as motor_cycle_model
      , mo.price as price
    from country con
    cross join motorcycle_model mo
   ) stock
left join sales sa on sa.model_id=stock.mid
                  and sa.country_id=stock.cid
                  and year(sa.sales_date) = 2018
group by 1,2
order by 1;

输出:

国家的名字 motor_cycle_model 收入
阿尔及利亚 摩托400 0
阿尔及利亚 YZM1000 0
多米尼克 摩托400 250000
多米尼克 YZM1000 140000
圣多美和普林西比 摩托400 0
圣多美和普林西比 YZM1000 560000

推荐阅读