如何在mysql中创建两年比较销售查询

6pp0gazn  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(306)

我有一张产品和销售表。sales表将product 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
deyfvvtc

deyfvvtc1#

如果你需要这两个年份你应该使用与否和

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

你不应该用数量分组
但为了比较,你可能需要

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
0h4hbjxa

0h4hbjxa2#

可以使用条件聚合:

select p.name,
       sum(case when s.year = 2019 then s.quantity end) as qty_2019,
       sum(case when s.year = 2020 then s.quantity end) as qty_2019,
from products as p left join
     sales as s   
     on s.product_id = p.id
group by p.name;
qkf9rpyu

qkf9rpyu3#

我想你想要两笔钱,一年一笔,而不是两年的总数。有几种方法可以做到这一点。一种是将两个和作为单独的子查询计算,并将它们连接起来:

SELECT a.name, a.sum AS sum2020, b.sum AS sum2019
FROM
  (select name, sum(quantity) AS sum from Products as P LEFT JOIN Sales AS S ON S.product_id = P.id where S.year = '2020') a
  JOIN
  (select name, sum(quantity) AS sum from Products as P LEFT JOIN Sales AS S ON S.product_id = P.id where S.year = '2019') b
  ON a.name = b.name;

另一个是计算两个条件列和的单个查询。

SELECT name,
   SUM(CASE WHEN S.year = '2020' THEN S.quantity ELSE 0 END) sum2020,
   SUM(CASE WHEN S.year = '2019' THEN S.quantity ELSE 0 END) sum2019,
FROM Products P
   LEFT JOIN Sales S
   ON S.product_id = P.id
   GROUP BY P.name

我不知道哪个更快,不同的人可能会发现一种方法或另一种概念上更简单。
顺便说一句,对于这样的查询,我喜欢从生成年份序列开始,交叉连接产品ID,然后将年度总计左键连接到交叉产品。这样,你就得到了年积的整个矩阵,可以在没有数据的地方放入零。如果不这样做,您可能会在某一产品一年内零销售额的数据中出现缺口,从而导致误导性的报告或具有奇数刻度的图表。

相关问题