sql 時間條件查詢


sql查詢當天所有記錄

to_date()使用

select * from table t where t.time >= to_date(aaaa,'yyyy-mm-dd hh24:mm:ss') and t.time<to_date(bbbb,'yyyy-mm-dd hh24:mm:ss')

aaaa,bbbb是字符串類型 比如:aaaa = '2018-04-19 00:00:00' bbbb = '2018-04-20 00:00:00'

to_date()中yyyy-mm-dd hh24:mm:ss 意思把aaaa字符串轉換成 yyyy-mm-dd hh24:mm:ss這樣的時間格式

select * from v$session where logon_time>=to_date('2018-04-19 00:00:00','yyyy-mm-dd hh24:mi:ss') and logon_time<to_date('2018-04-20 00:00:00','yyyy-mm-dd hh24:mi:ss');

trunc(sysdate)使用

select * from table t where t.time >= trunc(sysdate) and t.time < trunc(sysdate+1)

sysdate是oracle數據庫的系統當前時間 sysdate是時間格式的 trunc是oracle的截取函數 trunc(sysdate) 截取的結果是當前時間的yyyy-mm-dd 截取后也是如期類型

select * from v$session where logon_time>=trunc(sysdate) and logon_time<trunc(sysdate+1);

to_char()使用

select * from table t where to_char(t.time,'yyyy-mm-dd hh24:mm:ss') >= aaaa and to_char(t.time,'yyyy-mm-dd hh24:mm:ss')<bbbb

to_char()中t.time是表里的時間字段,先把t.time時間格式轉換成字符串'yyyy-mm-dd hh24:mm:ss' 然后再和字符串aaaa,bbbb比較

select * from v$session where to_char(logon_time,'yyyy-mm-dd hh24:mi:ss')>='2018-04-19 00:00:00' and to_char(logon_time,'yyyy-mm-dd hh24:mi:ss')<'2018-04-20 00:00:00';

------------------------------------------------------------------------------------------------------- 

to_date()和to_char()的區別在於to_date()把查詢條件字符串先轉換成時間格式,to_char()把待查詢的字段先轉換成字符串然后再和查詢條件字符串做比較

select * from dual where to_char(sysdate, 'yyyy-MM-dd') = '2019-04-04';
select * from dual where substr(sysdate, 0, 10) = to_date('2019-04-04', 'yyyy-MM-dd');//substr(sysdate,0,10)截取后仍為日期類型
select * from dual where sysdate > to_date('2019-04-04', 'yyyy-MM-dd');

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM