Filter data based on date in sql

痴心易碎 提交于 2019-12-07 10:55:52

问题


Im trying to execute the following SQL query and filter out the data based on the date.

I need to display a table which filters out the data such that, only those rows which are between the mentioned start_date and end_date

Here's the query that I have been trying

SELECT DISTINCT T1.column1, T1.column2, T2.START_DATE, T2.END_DATE
FROM Table1 T1, Table2 T2
WHERE (T1.column1= T2.column2) AND
(T2.START_DATE >= '15/01/2013 10:58:58' AND 
   T2.END_DATE <= '18/01/2013 10:58:58') ORDER BY T2.START_DATE DESC

I get the result with values from 2012 as well. Please help me out

Thanks


回答1:


Since you have not mentioned about any errors, if START_DATE and END_DATE are DATETIME data type, there is nothing wrong with your query. If you are not getting the correct records, Please check the data.

However your date format may trouble you in a different server. There are some good practices you could adhere to avoid such issues.

-Whenever date is used as a string, try to use it in ISO or ISO8601 format (ie 'yyyymmdd' or 'yyyy-mm-ddThh:mi:ss.mmm')

-Also avoid joining tables with WHERE Table1, Table2 which is old and obsolete. JOINs are much better performed, neat and tidy.

You can change your query as follows;

SELECT DISTINCT T1.column1, T1.column2, T2.START_DATE, T2.END_DATE
FROM Table1 T1 JOIN Table2 T2 ON T1.column1 = T2.column2
WHERE (T2.START_DATE >= '20130115 10:58:58' AND 
       T2.END_DATE <= '20130118 10:58:58') 
ORDER BY T2.START_DATE DESC


来源:https://stackoverflow.com/questions/14397569/filter-data-based-on-date-in-sql

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