尝试查找不同的数据时,取回相同的结果

时间:2012-08-15 02:59:11

标签: sql database postgresql date postgresql-8.4

我可以从下面的查询中获取每年的15/02 - 21/06日期范围数据。

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)

但问题是,当我想从年2010 - 2012找到时,我会得到相同的结果。

我想得到的范围:

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

谁可以帮我解决这个问题!

1 个答案:

答案 0 :(得分:3)

你的问题是缺少括号:在SQL中AND优先于OR,所以你需要在前面的整个表达式中加上括号:

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

如果没有括号,则会获得A or B or (C and D),但您需要(A or B or C) and D