Oracle SQL comparison of DATEs returns wrong result

后端 未结 2 1479
青春惊慌失措
青春惊慌失措 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
    

提交回复
热议问题