今天調整報表檢索條件的時候遇到to_date()格式化日期的問題,明細如下:
1.總數據 159條
select * from daily_file_information;
2.查詢每月數據 3月-139條 4月-16條 5月-4條
select to_char(dfi_create_time,'yyyy-mm'),count(1) from daily_file_information group by to_char(dfi_create_time,'yyyy-mm');
3.第一種查詢方式 【…between…and…】
SQL1:結果159條
select count(1) from daily_file_information where 1=1 and to_char(dfi_create_time,'yyyy-mm') between '2020-03' and '2020-05' ;
SQL2:結果155條
select count(1) from daily_file_information where 1=1 and dfi_create_time between to_date('2020-03','yyyy-mm') and to_date('2020-05','yyyy-mm') ;
4.第二種查詢方式 【…大於等於…小於等於…】
SQL3:結果159條
select count(1) from daily_file_information where 1=1 and to_char(dfi_create_time,'yyyy-mm') >= '2020-03' and to_char(dfi_create_time,'yyyy-mm') <= '2020-05' ;
SQL4:結果155條
select count(1) from daily_file_information where 1=1 and dfi_create_time >= to_date('2020-03','yyyy-mm') and dfi_create_time <= to_date('2020-05','yyyy-mm') ;
5.差異數據:to_date()格式化4條5月份數據
to_date(‘2020-05’) 結果爲:2020/05/01
結論:
經過幾個SQL的查詢方式對比發現以to_date()轉換數據查詢的結果可能與預期結果數據不一致。
一般情況下在做類似時間過濾的時候我還是比較喜歡用to_char()的方式,根據這幾個查詢的結論而言還是建議大家慎用to_date()這個函數。
我是二哥(Jayla),每天總結一點點,每天進步一點點。
我是二哥(Jayla),歡迎大家關注我的公衆號:
每天總結一點點,每天進步一點點。
專注Java相關知識,每天準時分享乾貨。 SpringBoot/Oracle/Git/Linux/Mysql 期待您的加入~