里上图 表 aaa, 要按月份查找,a 出现的次数,代码如下
SELECTCAST(YEAR(rq) as varchar) + '-' + CAST(MONTH(rq) as varchar) AS date,
count(*) AS '次数'
FROM aaa
where a="a"
GROUP BY
CAST(YEAR(rq) as varchar) + '-' + CAST(MONTH(rq) as varchar)
结果如下图,看看是不是你要的
数据表中不存在的月份也要显示,建议创建一个从1到12月份的表作为比对表。如果不方便创建月份比对表则可以用select 1到12的办法来虚拟这个月份比对表,但是语句会有些冗长。请参考下列写法:
select months.year,months.month,concat(ifnull(t.sumMonthNum,'0'),
'/',months.sumYearNum) as `月/年比`
from
(select * from
(select year(time) as year,
sum(num) as sumYearNum
from abc group by year(time)) years,
(select 1 as month union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10 union all
select 11 union all
select 12) months) months left join
(select year(time) as year,
month(time) as month,
sum(num) as sumMonthNum
from abc group by year(time),month(time)) t
on months.month=t.month
order by months.year,months.month
实验截图如下:
源表数据
SQL代码及运行结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)