SQL查询最近1天、7天、30天、本月、上一月数据

formIdList表名,createTime字段,只需改这俩

几个小时内的数据

DATE_SUB(NOW(), INTERVAL 5 HOUR)

今天

select * from formIdList where to_days(createTime) = to_days(now());

昨天

SELECT * FROM formIdList WHERE TO_DAYS( NOW( ) ) - TO_DAYS( createTime) <= 1

7天

SELECT * FROM formIdList where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(createTime)

近30天

SELECT * FROM formIdList where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(createTime)

本月

SELECT * FROM formIdList WHERE DATE_FORMAT( createTime, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )

上一月

SELECT * FROM formIdList WHERE PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( createTime, '%Y%m' ) ) =1

你可能感兴趣的:(SQL)