mysql - 使用 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 年没有销售的国家/地区。
解决方案
尝试:
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
(因为我有它的名字),然后对sales
2018 年进行左连接。
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 |
推荐阅读
- python - 在终端中输入“conda list”时列出了什么?
- c# - 如何稍后用行和其他列填充一个数据表列?
- r - 使用 quantreg 获取模型的显着性水平(p 值)
- php - PHP - 只有在迭代之间发生变化时才循环遍历数组并打印出值
- android - 从文件描述符上的相机错误返回图像
- python - 如何在菜单栏中实现刷新按钮以刷新所有组合框项的原始状态?
- python - Keras LSTM 拟合欠拟合
- javascript - Angular:使用 ControlValueAccessor 自定义输入
- python - 如何将行数堆叠到一行并分配id
- mongodb - .gitlab-ci.yml 中的 Mongodb 副本集