我有一张表,上面有项目和添加日期。我想要的是按年和月得到一份增加项目的报告。
我的问题是:
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),但它们都没有用。我卡住了。
发布于 2018-07-16 12:27:35
试试这个:
--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发布于 2018-07-16 12:35:09
这将适用于mysql工作台中的情况。
Select ifnull(count(*),0) from [TABLE NAME]https://stackoverflow.com/questions/51361523
复制相似问题