首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MYSQL计数为空;

MYSQL计数为空;
EN

Stack Overflow用户
提问于 2018-07-16 12:09:53
回答 2查看 47关注 0票数 0

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

我的问题是:

代码语言:javascript
复制
SELECT COUNT(*) FROM items 
GROUP BY YEAR(FROM_UNIXTIME(items.added)), MONTH(FROM_UNIXTIME(items.added))

查询返回

代码语言:javascript
复制
+----------+
| COUNT(*) |
+----------+
|       45 |
|       22 |
|        8 |
|       12 |
|       27 |
+----------+

这是正确的数据,但我也希望从过去3年没有添加任何项目的月份中获得0。并获得列名为YEAR - MONTH

我试过SELECT IF(COUNT(*) IS NULL, 0, COUNT(*))SELECT IFNULL(COUNT(*), 0),但它们都没有用。我卡住了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-16 12:27:35

试试这个:

代码语言:javascript
复制
--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
EN

Stack Overflow用户

发布于 2018-07-16 12:35:09

这将适用于mysql工作台中的情况。

代码语言:javascript
复制
Select ifnull(count(*),0) from [TABLE NAME]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51361523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档