資料庫中SQL查詢指定日期內資料

2021-07-16 10:28:00 字數 2137 閱讀 7486

mysql資料庫:

有時我們面要統計一下資料庫中指定日期的資料,如常用的,今天,昨天,明天,本週、上週、本月、上個月份的資料,除了我們可以使用strtotime來算還可以參考下面方法。

今天select * from 表名 where to_days(時間欄位名)=to_days(now());

昨天

select * from `表名` where to_days(now()) – to_days(時間欄位名) = 1;

/*datediff(now() , from_unixtime(`時間欄位名`)) = 1; //時間字段 儲存型別為時間戳*/

7天select * from `表名` where date_sub(curdate(), interval 7 day) <= date(時間欄位名);

/*datediff(now() , from_unixtime(`時間欄位名`)) = 7; //時間字段 儲存型別為時間戳*/

近30天select * from 表名 where date_sub(curdate(), interval 30 day) <= date(時間欄位名);

本月select * from 表名 where date_format(時間欄位名, '%y%m' = date_format(curdate(), '%y%m';

查詢當前這週的資料

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(); 

查詢上個月的資料

select name,submittime from enterprise   where date_format(submittime,'%y-%m')=date_format(date_sub(curdate(), interval 1 month),'%y-%m') 

select * from `user` where date_format(pudate,'%y%m') = date_format(curdate(),'%y%m') ; 

select * from user where weekofyear(from_unixtime(pudate,'%y-%m-%d')) = weekofyear(now()) 

select *  from user where month(from_unixtime(pudate,'%y-%m-%d')) = month(now()) 

select *  from [user]  where year(from_unixtime(pudate,'%y-%m-%d')) = year(now()) 

and month(from_unixtime(pudate,'%y-%m-%d')) = month(now()) 

從指定日期中獲取部分資料:

如月份:

select to_char(sysdate,'mm') from dual;

或者:

select extract(month from sysdate) from dual;

mysql根據時間戳查詢指定日期內資料

mysql查詢時間段的方法未必人人都會,下面為您介紹兩種mysql查詢時間段的方法,供您參考,希望對您能有所啟迪。mysql的時間欄位有date time datetime timestamp等,往往我們在儲存資料的時候將整個時間存在乙個欄位中,採用datetime型別 也可能採用將日期和時間分離,...

指定日期查詢數Oracle據庫

1,首先,介紹一下to char函式 to char 是把日期或數字轉換為字串,不能指定字串長度。使用to char函式處理日期 to char number,格式 例如 to char salary,99,999.99 使用to char函式處理日期 to char date,格式 to char...

sql查詢指定日期前n天資料

查詢2019 08 28前7天的記錄,包括2019 08 28 select from a where timestampdiff day,a.create time,2019 08 28 7 and timestampdiff day,a.create time,2019 08 28 0擴充套件 ...