Oracle SQL comparison of DATEs returns wrong result

后端 未结 2 1466
青春惊慌失措
青春惊慌失措 2020-12-06 22:52

I have REPORTDATE column in database (DATETIME) type. I want to extract only DATE value from the DATETIME, then to do COUNT

相关标签:
2条回答
  • 2020-12-06 23:33

    WHERE to_char(REPORTDATE, 'DD.MM.YYYY')>'09.11.2013'

    You are comparing two STRINGS. You need to compare the DATEs. As I already said in the other answer here, you need to leave the date as it is for DATE calculations. TO_CHAR is for display, and TO_DATE is to convert a string literal into DATE.

    SELECT TO_CHAR(REPORTDATE, 'DD.MM.YYYY'),
      COUNT(*)
    FROM TABLE
    WHERE REPORTDATE > TO_DATE('09.11.2013', 'DD.MM.YYYY')
    GROUP BY TO_CHAR(REPORTDATE, 'DD.MM.YYYY') 
    

    Also, REPORTDATE is a DATE column, hence it will have datetime element. So, if you want to exclude the time element while comparing, you need to use TRUNC

    WHERE TRUNC(REPORTDATE) > TO_DATE('09.11.2013', 'DD.MM.YYYY')
    

    However, applying TRUNC on the date column would suppress any regular index on that column. From performance point of view, better use a Date range condition.

    For example,

    WHERE REPORTDATE
    BETWEEN 
            TO_DATE('09.11.2013', 'DD.MM.YYYY')
    AND     
            TO_DATE('09.11.2013', 'DD.MM.YYYY') +1
    
    0 讨论(0)
  • 2020-12-06 23:35

    The condition to_char(REPORTDATE, 'DD.MM.YYYY')>'09.11.2013' compare to strings, so 30.10.2013 is after 09.11.2013. You need to compare the dates, not the string values, so you have to change your query to the following.

    SELECT to_char(REPORTDATE, 'DD.MM.YYYY') AS MY, COUNT(1) 
    from INCIDENT
    where trunc(REPORTDATE)> to_date('09.11.2013', 'DD.MM.YYYY')
    GROUP BY to_char(REPORTDATE, 'DD.MM.YYYY')
    

    Note: I added a little modification from count(*) to count(1) for optimize the query having the same results.

    0 讨论(0)
提交回复
热议问题