首页 > 解决方案 > 如何在 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
     

标签: mysqlsql

解决方案


如果你需要这两个年份,你应该使用 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

推荐阅读