mysql count nulls;

qrjkbowd  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(317)

我有一张表,上面有项目和添加日期。我想要的是得到一份按年度和月份添加项目的报告。
我的问题:

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

查询返回

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

这是正确的数据,但我也想得到 0 从最近3年内没有增加项目的月份开始。并将列名作为 YEAR - MONTH .
我试过了 SELECT IF(COUNT(*) IS NULL, 0, COUNT(*)) 还有 SELECT IFNULL(COUNT(*), 0) 但都没用。我卡住了。

xwbd5t1u

xwbd5t1u1#

试试这个:

--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
68bkxrlz

68bkxrlz2#

这将适用于mysql工作台中的条件。

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

相关问题