牛骨文教育服务平台(让学习变的简单)
博文笔记

使用mysql实现1-12月份查询统计

创建时间:2017-01-05 投稿人: 浏览次数:154

在数据中我们应该如何实现1-12月份统计的查询,今天一个哥们一起探讨这个问题,我想出来了一个方法,但是不便统计,同学使用的oracle,用oracle实现了一种查询。

实现的效果如下:

首先说下我的sql方式:

-- 创建表测试
create table lesson(
	id int auto_increment primary key,
	stuName varchar(60),
	time datetime
);

创建完成后添加数据测试

查询的sql如下:

select t.myYear as 年份,t.monthNo as 月份,count(1) as 数量统计
from(select month(lesson.time) as monthNo,
         year(lesson.time) as myYear,
     lesson.id as id
 from lesson) as t
where t.myYear="2016"
group by t.monthNo;

结果如下:

同学使用的是oracle:大致思路是写12个sum(decode(to_char(lesson.time,"mm"),"01",1,0)),然后实现查询,最终能够实现每个月多少数据量,方便查询。

我考虑了一会儿,模仿他的方式用mysql实现了这样的查询,虽然简单,但是确实能够解决实际问题:

-- 统计方法二
select 
sum(case month(lesson.time) when "1" then 1 else 0 end) as 一月份,
sum(case month(lesson.time) when "2" then 1 else 0 end) as 二月份,
sum(case month(lesson.time) when "3" then 1 else 0 end) as 三月份,
sum(case month(lesson.time) when "4" then 1 else 0 end) as 四月份,
sum(case month(lesson.time) when "5" then 1 else 0 end) as 五月份,
sum(case month(lesson.time) when "6" then 1 else 0 end) as 六月份,
sum(case month(lesson.time) when "7" then 1 else 0 end) as 七月份,
sum(case month(lesson.time) when "8" then 1 else 0 end) as 八月份,
sum(case month(lesson.time) when "9" then 1 else 0 end) as 九月份,
sum(case month(lesson.time) when "10" then 1 else 0 end) as 十月份,
sum(case month(lesson.time) when "11" then 1 else 0 end) as 十一月份,
sum(case month(lesson.time) when "12" then 1 else 0 end) as 十二月份
from lesson
where year(lesson.time)="2016";

最后运行的结果为:

好了,以上就是整体的思路,如果你还有更好的想法,请留言~

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。