【Mysql】关于日期时间的一些操作

关于mysql时间函数

日期常用函数

now() 		 返回当前日期和时间
CURDATE()    返回当前日期
DATE_ADD()   添加时间
DATE_SUB()   减去时间
DATEDIFF()   返回两个日期之间的天数
DATE_FORMAT()日期时间格式化

示例

1、获取今天的所有数据

select * from t_table 
where date_format(createtime,'%Y-%m-%d')= date_format(now(),'%Y-%m-%d') 

2、获取昨天的所有数据

select * from t_table 
where date_format(createtime,'%Y-%m-%d')= date_format(NOW() - inTERVAL 1 DAY,'%Y-%m-%d')

3、获取近一小时的所有数据

select * from t_table  where createtime >  date_sub(now(), INTERVAL  1 hour) 

4、获取当年的所有信息

select * from t_table where date_format(createtime,'%Y') = date_format(now(),'%Y')
select * from t_table where year(createtime) = year(now())

5、查询年龄分布

#查党龄年龄分布
#根据入党时间来查询党龄
select 
(case
when dp.partystanding <10 then '10年以下'
when dp.partystanding between 10 and 19 then '10-20年'
when dp.partystanding between 20 and 29 then '20-30年'
when dp.partystanding between 30 and 39 then '30-40年'
when dp.partystanding between 40 and 50 then '40-50年'
when dp.partystanding >50 then '50年以上'
end ) name,count(*) value
from
(select  TIMESTAMPDIFF(YEAR, PartyDate, CURDATE()) partystanding from dy_pres30101000011_001 where BelongZZ like '%XX镇%' ) dp 
group by name
posted @ 2021-09-14 14:14  念月_xy  阅读(223)  评论(0编辑  收藏  举报