数据表中不存在的月份也要显示,建议创建一个从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代码及运行结果
--查询员工表中本月聘用的员工数目select count(*) count
from employees e
where e.hire_date>=TRUNC(SYSDATE, 'MM')
and e.hire_date<=LAST_DAY(SYSDATE)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)