Get back the same result when trying to find different data

怎甘沉沦 提交于 2020-01-15 11:19:13

问题


I can get the 15/02 - 21/06 date range data on every year from the query below.

SELECT * FROM dim_date
WHERE EXTRACT (MONTH FROM date_cal) BETWEEN 3 AND 5
 OR (EXTRACT (MONTH FROM date_cal) = 2 AND EXTRACT (DAY FROM date_cal) >= 15)
 OR (EXTRACT (MONTH FROM date_cal) = 6 AND EXTRACT (DAY FROM date_cal) <= 21)

But the problem is, when i want to find from year 2010 - 2012, I get back the same result.

Range that i want to get:

2010-02-15 - 2010-06-15
2011-02-15 - 2011-06-15
2012-02-15 - 2012-06-15

SELECT * FROM dim_date
WHERE EXTRACT (MONTH FROM date_cal) BETWEEN 3 AND 5
 OR (EXTRACT (MONTH FROM date_cal) = 2 AND EXTRACT (DAY FROM date_cal) >= 15)
 OR (EXTRACT (MONTH FROM date_cal) = 6 AND EXTRACT (DAY FROM date_cal) <= 21)
AND EXTRACT (YEAR FROM date_cal) BETWEEN 2010 AND 2012

Who can help me about this!


回答1:


Your problem is a lack of brackets: In SQL AND takes precedence over OR, so you need to put brackets around your whole previous expression:

SELECT * FROM dim_date
WHERE ( -- added bracket
 EXTRACT (MONTH FROM date_cal) BETWEEN 3 AND 5
 OR (EXTRACT (MONTH FROM date_cal) = 2 AND EXTRACT (DAY FROM date_cal) >= 15)
 OR (EXTRACT (MONTH FROM date_cal) = 6 AND EXTRACT (DAY FROM date_cal) <= 21)
 ) -- added bracket
AND EXTRACT (YEAR FROM date_cal) BETWEEN 2010 AND 2012

Without the brackets, you get A or B or (C and D), but you want (A or B or C) and D



来源:https://stackoverflow.com/questions/11963564/get-back-the-same-result-when-trying-to-find-different-data

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