MYSQL计数为空;

时间:2018-07-16 12:09:53

标签: mysql sql

我有一张桌子,上面有物品和它们的添加日期。我想要的是按年份和月份获得添加项目的报告。

我的查询:

SELECT COUNT(*) FROM items 
GROUP BY YEAR(FROM_UNIXTIME(items.added)), MONTH(FROM_UNIXTIME(items.added))

查询返回

+----------+
| COUNT(*) |
+----------+
|       45 |
|       22 |
|        8 |
|       12 |
|       27 |
+----------+

这是正确的数据,但我也想从最近3年未添加任何项目的月份中获取0。并获得列名称为YEAR - MONTH

我尝试了SELECT IF(COUNT(*) IS NULL, 0, COUNT(*)),也尝试了SELECT IFNULL(COUNT(*), 0),但没有一个有效。我被卡住了。

2 个答案:

答案 0 :(得分:1)

尝试一下:

--creation of calendar table
create table months(month int);
insert into months values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12);
create table years(year int);
insert into years values (2017),(2018); --here you specify for what years you want to have summary
create table calendarTable(month int, year int);
insert into calendarTable
select month, year from months cross join years;

select ct.year, ct.month, sum(case when i.added is null then 0 else 1) from calendarTable ct
left join items i on ct.year = YEAR(FROM_UNIXTIME(i.added)) and ct.month = MONTH(FROM_UNIXTIME(i.added))
group by ct.year, ct.month

答案 1 :(得分:1)

这将适合您在mysql工作台中的条件。

Select ifnull(count(*),0) from [TABLE NAME]