【发布时间】:2016-01-09 15:50:29
【问题描述】:
我有一张带行李的桌子,上面有柱子:
status(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..
我想每年每季度统计一张表中状态为“丢失”的行李件。 同时还返回没有“丢失”件的宿舍(计数 = 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。
希望有人可以帮助我查询(可能是临时表?),为我提供所需的表!
【问题讨论】:
标签: mysql sql date temp-tables