Oracle SQL comparison of DATEs returns wrong result

谁说我不能喝 提交于 2019-11-26 21:57:56

问题


I have REPORTDATE column in database (DATETIME) type. I want to extract only DATE value from the DATETIME, then to do COUNT for each day and to put WHERE clause to restrict only dates later than some specific date.

So I have this clause:

SELECT to_char(REPORTDATE, 'DD.MM.YYYY') AS MY, COUNT(*) from INCIDENT
where to_char(REPORTDATE, 'DD.MM.YYYY')>'09.11.2013'

GROUP BY to_char(REPORTDATE, 'DD.MM.YYYY')

It returns me results but but I can notice wrong result such as : 30.10.2013 which is wrong result.

How to solve this?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/29005398/oracle-sql-comparison-of-dates-returns-wrong-result

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