sql按日期查询

今天有一个需求:根据录入时间查询出近一周,近一月,近一年的数据
数据库如下:
在这里插入图片描述
这里使用到的SQL语句:
利用to_days函数查询今天的数据:

select * from 表名 where to_days(时间字段名) = to_days(now());

to_days函数:返回从0000年(公元1年)至当前日期的总天数
昨天

SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) – TO_DAYS( 时间字段名) <= 1;

近一周:

select * from sqxx where TO_DAYS(now()) - TO_DAYS(bxsj) <=7

近一月:

select * from sqxx where date_sub(curdate(), INTERVAL 30 DAY) <= date(bxsj)

SQL DATE_SUB 是一个mySql函数。不象SQL DATE_ADD 函数 增加时间值,SQL DATE_SUB 将从一个日期/时间值中减去一个时间值(时间间隔)。

SQL DATE_SUB 语法

DATE_SUB(日期表达式, INTERVAL expr type)  

Type 值

	MICROSECOND
	SECOND
	MINUTE
	HOUR
	DAY
	WEEK
	MONTH
	QUARTER
	YEAR
	SECOND_MICROSECOND
	MINUTE_MICROSECOND
	MINUTE_SECOND
	HOUR_MICROSECOND
	HOUR_SECOND
	HOUR_MINUTE
	DAY_MICROSECOND
	DAY_SECOND
	DAY_MINUTE
	DAY_HOUR
	YEAR_MONTH
	SQL DATE_SUB 

范例

SELECT DATE_SUB('2010-08-12', INTERVAL 3 DAY) AS NewDate ;

结果: 2010-08-09

SELECT DATE_SUB('2010-08-12', INTERVAL '3-2' YEAR_MONTH) AS NewDate;

结果: 2007-06-12

SELECT DATE_SUB('2011-09-14 2:44:36', INTERVAL '2:26' HOUR_MINUTE) AS NewDate  

结果: 2011-09-14 00:18:36
近一年:

select * from sqxx where YEAR(bxsj)=YEAR(NOW())

7天

SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(时间字段名)

近30天

SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(时间字段名)

本月

SELECT * FROM 表名 WHERE DATE_FORMAT( 时间字段名,%Y%m' ) = DATE_FORMAT( CURDATE( ) , ‘%Y%m' )

上一月

SELECT * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) ,%Y%m' ) , date_format( 时间字段名, ‘%Y%m' ) ) =1
#查询本季度数据
select * from `ht_invoice_information` where QUARTER(create_date)=QUARTER(now());
#查询上季度数据
select * from `ht_invoice_information` where QUARTER(create_date)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));
#查询本年数据
select * from `ht_invoice_information` where YEAR(字段)=YEAR(NOW());
#查询上年数据
select * from `ht_invoice_information` where year(字段)=year(date_sub(now(),interval 1 year));
#查询当前这周的数据
SELECT name,submittime FROM enterprise WHERE YEARWEEK(date_format(submittime,'%Y-%m-%d')) = YEARWEEK(now());
#查询上周的数据
SELECT name,submittime FROM enterprise WHERE YEARWEEK(date_format(submittime,'%Y-%m-%d')) = YEARWEEK(now())-1;
查询当前月份的数据
select name,submittime from enterprise where date_format(submittime,'%Y-%m')=date_format(now(),'%Y-%m')
#查询距离当前现在6个月的数据
select name,submittime from enterprise where submittime between date_sub(now(),interval 6 month) and now();
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页