常用SQL整理
常用SQL整理
查询当天、本周、本月、本年的数据
查询天
1 2
| select * from tb where DATE(create_time) = curdate()
|
查询周
1 2 3 4 5 6 7
| select * from tb where YEARWEEK(date_format(create_time,'%Y-%m-%d')) = YEARWEEK(now())
SELECT * FROM tb WHERE WEEK(create_time)=WEEK(DATE_SUB(NOW(),INTERVAL 1 WEEK)) AND YEAR(create_time) = YEAR(NOW())
select * from tb where date_sub(curdate(), interval 7 day) <= date(create_time)
|
查询月
1 2 3 4 5
| select * from tb where date_format(create_time,'%Y-%m') = date_format(now(),'%Y-%m')
select * from tb where date_format(create_time, '%Y-%m')=date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y-%m')
|
查询季度
1 2 3 4 5
| SELECT * FROM tb WHERE QUARTER(create_time)=QUARTER(NOW()) AND YEAR(create_time) = YEAR(NOW())
SELECT * FROM tb WHERE QUARTER(create_time)=QUARTER(DATE_SUB(NOW(),INTERVAL 1 QUARTER)) AND YEAR(create_time) = YEAR(NOW())
|
查询年
1 2 3 4
| select * from tb where date_format(create_time,'%Y') = date_format(now(),'%Y')
SELECT * FROM tb WHERE YEAR(create_time)=YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR))
|