每季度每季度MySQL计数,计数为0

时间:2016-01-09 15:50:29

标签: mysql sql date temp-tables

我有一张带行李的桌子,上面有列:

状态(VARCHAR) - (“丢失”,“找到”等)

datefound(DATE) - (YYYY-MM-DD)

我的行李桌:

   -------------------------------------------
  | status | otherattributes |   datefound    |
   -------------------------------------------
  | lost   | ............... |   2014-11-17   |
  | found  | ............... |   2015-05-28   |
  | lost   | ............... |   2016-11-17   |
  | lost   | ............... |   2015-10-20   |
                     etc..

我想每年每季度在表格中计算行李件的状态为“丢失”。 虽然ALSO返回的地方没有“丢失”部分(计数= 0)。

我想要的是什么:

所需的表格看起来像这样:

   ------------------------------
  | year | quarter | amountlost |
   ------------------------------
  | 2014 |    1    |     23     |
  | 2014 |    2    |     41     |
  | 2014 |    3    |      0     |
  | 2014 |    4    |     12     |
  | 2015 |    1    |     32     |
  | 2015 |    2    |      0     |
  | 2015 |    3    |      9     |
  | 2015 |    4    |     27     |
  | 2016 |    1    |     53     |
  | 2016 |    2    |     24     |
  | 2016 |    3    |     11     |
  | 2016 |    4    |      0     |
   ------------------------------

我现在拥有的:

我目前有一个查询,但它没有返回COUNT为0的年份+季度。我已经尝试使用临时表但我无法让它工作..

我正在使用的当前查询:

(未给出期望的结果)

SELECT YEAR(datefound) AS year, QUARTER(datefound) AS quarter, COUNT(status) AS amountlost FROM luggage WHERE status = 'lost' GROUP BY YEAR(datefound), QUARTER(datefound) ORDER BY YEAR(datefound), QUARTER(datefound)

导致(不需要):

   ------------------------------
  | year | quarter | amountlost |
   ------------------------------
  | 2014 |    4    |     10     |
  | 2015 |    1    |     32     |
  | 2015 |    2    |      0     |
  | 2015 |    3    |      9     |
  | 2015 |    4    |     27     |
  | 2016 |    1    |     53     |
   ------------------------------

上面的表格 2014年和2016年的缺失季度,这将导致0计数@ amountlost。

希望有人可以帮我解决问题(可能还有临时表?),它为我提供了所需的表格!

1 个答案:

答案 0 :(得分:0)

这是您有两种选择的情况。输入数据具有所有年份和季度时更容易,但where子句将其过滤掉。然后你可以切换到条件聚合:

SELECT YEAR(datefound) AS year, 
       QUARTER(datefound) AS quarter, 
       SUM(status = 'lost') AS amountlost
FROM luggage
GROUP BY YEAR(datefound), QUARTER(datefound)
ORDER BY YEAR(datefound), QUARTER(datefound);

如果这不起作用,则需要生成可能的行,然后添加其他信息。假设数据中每年和每季度都有代表:

SELECT y.yyyy, q.qq, COUNT(l.status) as AmountLost
FROM (SELECT DISTINCT YEAR(datefound) as yyyy FROM luggage) y CROSS JOIN
     (SELECT DISTINCT QUARTER(datefound) as qq FROM LUGGAGE) q LEFT JOIN
     luggage l
     ON YEAR(l.datefound) = y.yyyy AND QUARTER(l.datefound) = q.qq AND
        l.status = 'lost'
GROUP BY y.yyyy, q.qq;

如果您的数据在这方面甚至不完整,那么您需要生成所需的行。类似的东西:

SELECT yq.yyyy, yq.qq, COUNT(l.status) as AmountLost
FROM (SELECT 2014 as yyyy, 1 as qq  UNION ALL
      SELECT 2014, 2 UNION ALL
      . . .
     ) yq LEFT JOIN
     luggage l
     ON YEAR(l.datefound) = yq.yyyy AND QUARTER(l.datefound) = yq.qq AND
        l.status = 'lost'
GROUP BY yq.yyyy, yq.qq;

注意:您可能已经有一张表格,其中包含报告的相应年份和季度。如果是这样,你可以使用它。如果您有某种数字表,也可以使用(带有一些额外的逻辑)。