mysql - 如何在 mysql 中创建两年比较销售查询
问题描述
我有一个产品和销售表。销售表将产品 ID 作为外键,其中包含每个产品的销售日期和销售数量。我想根据销售的产品数量生成年度比较报告。因此,该报告将包含 2019 年和 2020 年等年份的所有产品,每个产品的数量总和显示在 2019 年和 2020 年以下。我已经编写了此查询,但无法正常工作。
select p.name, sum(s.quantity) as qty from products as p
left join sales as s
on s.product_id = p.id
where s.year == '2019' and s.year == '2020' group by p.name, s.quantity
解决方案
如果你需要这两个年份,你应该使用 OR 而不是 AND
select s.year, p.name, sum(s.quantity) as qty
from products as p
left join sales as s on s.product_id = p.id
AND s.year = '2019' OR s.year == '2020'
group by p.name,s.year
并且您不应该在 group by 中使用数量
但为了比较可能是你需要的
select p.name, sum(s1.quantity) qty_2019, sum(s2.quantity) qty_2020
from products as p
left join sales s1 as s on s1.product_id = p.id
AND s1.year = '2019'
left join sales s2 as s on s2.product_id = p.id
AND s1.year = '2020' group by p.name,s.year
推荐阅读
- android - 位图无法在线性布局中正确加载
- angular - 重新实例化数据时,Angular CDK 拖放列表会中断
- java - 强制客户端或服务器重新启动 SSL 握手(或使 SSL 会话过期)
- java - Intellij 警告:布尔方法 foo() 总是被反转
- javascript - 字符串中的替代大写
- matlab - 可以在运行时更改属性属性
- java - 如何使用 java 流对子列表中的元素进行分组和计数
- python - TensorFlow CNN 训练无故停止
- python-3.x - Robot Framework 中未找到变量错误
- c++ - C++加班/工资/时间半/双倍时间