Unable to fetch the records on TO DATE Oracle

旧城冷巷雨未停 提交于 2020-03-15 07:19:42

问题


Database - Table

 PROD.APPLICATION 
Game ID    Generated Date

 1          Jan-01-1995
 2          Aug-19-2003
 3          Nov-04-2001
 4          Sep-26-2007
 5          Sep-26-2007
 6          Sep-26-2007
 7          Sep-19-2007
 8          Sep-19-2007
 9          Sep-19-2007
10          Jan-11-1985
11          MAY-19-2003
12          Sep-22-2007
13          Sep-22-2007

I ran the following query

SELECT *
FROM PROD.APPLICATION JOIN PROD.STATUS ON (PROD.STATUS_ID = REF_STATUS.STATUS_ID)  

AND PROD.APPLICATION.GENERETED_DT >= to_date('2007-09-19', 'yyyy-MM-dd') AND     
    PROD.APPLICATION.GENERETED_DT <= to_date('2007-09-26', 'yyyy-MM-dd');

to search for the records from Sep 19 2007 to Sep 26 2007 ie 8 records.

Which has resulted in showing the only records for Sep 19 2007 znd Sep 22 2007 ie only 5 records

Actual Output
Game ID    Generated Date
7 Sep-19-2007
8 Sep-19-2007
9 Sep-19-2007
12 Sep-22-2007
13 Sep-22-2007

How to generate the search query so that I could get all the 8 records - ie the records on those dates aswell

Expected Output

 4 Sep-26-2007
 5 Sep-26-2007
 6 Sep-26-2007
 7 Sep-19-2007
 8 Sep-19-2007
 9 Sep-19-2007
12 Sep-22-2007
13 Sep-22-2007

Tried

SELECT *
FROM PROD.APPLICATION JOIN PROD.STATUS ON (PROD.STATUS_ID = REF_STATUS.STATUS_ID)  

AND PROD.APPLICATION.GENERETED_DT >= to_date('2007-09-19', 'yyyy-MM-dd') AND     
    PROD.APPLICATION.GENERETED_DT = to_date('2007-09-26', 'yyyy-MM-dd');

Revived No records


回答1:


The date probably has a time component. This is part of the date data type in Oracle -- but is often not shown when you query.

A better approach uses the following logic:

SELECT *
FROM PROD.APPLICATION A JOIN
     PROD.STATUS S
     ON A.STATUS_ID = S.STATUS_ID  
WHERE A.GENERATED_DT >= DATE '2007-09-19' AND
      A.GENERATED_DT < DATE '2007-09-27';

Notes:

  • The < DATE '2007-09-27' will include all datetimes from the day before.
  • The DATE keyword introduces a date constants with the format YYYY-MM-DD.
  • Table aliases make the query easier to write and to read.
  • Moving the condition to the WHERE clause has no effect on the query, but such filtering is more commonly done in the WHERE clause for an INNER JOIN.



回答2:


This truncates the time part in APPLICATION.GENERETED_DT and then compares it to the date on the right side.


SELECT *
FROM PROD.APPLICATION JOIN PROD.STATUS ON (PROD.STATUS_ID = REF_STATUS.STATUS_ID)  
AND trunc(PROD.APPLICATION.GENERETED_DT) >= to_date('2007-09-19', 'yyyy-MM-dd') AND     
    trunc(PROD.APPLICATION.GENERETED_DT) <= to_date('2007-09-26', 'yyyy-MM-dd');


来源:https://stackoverflow.com/questions/60331445/unable-to-fetch-the-records-on-to-date-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!