仅比较年份和月份

时间:2014-03-14 19:43:52

标签: sql db2

我用它来比较年份和月份,但是当月份小于当月时失败,即使年份大于当前年份

SELECT * FROM DUMMY_TABLE WHERE
YEAR(PREV_ELIG_REV_DT) >= YEAR(CURRENT TIMESTAMP)
AND MONTH(PREV_ELIG_REV_DT) >= MONTH(CURRENT TIMESTAMP)

2 个答案:

答案 0 :(得分:4)

当YEAR相等时,您可以添加额外条件以匹配情况。

SELECT * 
  FROM DUMMY_TABLE 
  WHERE
     YEAR(PREV_ELIG_REV_DT) > YEAR(CURRENT TIMESTAMP)
  OR (    YEAR(PREV_ELIG_REV_DT) = YEAR(CURRENT TIMESTAMP)
     AND MONTH(PREV_ELIG_REV_DT) >= MONTH(CURRENT TIMESTAMP))

<强>更新

正如@ Clockwork-Muse所说,可能产生更好性能的另一种方法是获得本月的开头并与之比较:

SELECT * 
  FROM DUMMY_TABLE 
  WHERE
     PREV_ELIG_REV_DT >= (CURRENT DATE - (DAY(CURRENT DATE)-1) DAYS)

答案 1 :(得分:0)

试试这个

SELECT * FROM DUMMY_TABLE 
WHERE
     YEAR(PREV_ELIG_REV_DT)*100 + MONTH(PREV_ELIG_REV_DT) 
  >= YEAR(CURRENT TIMESTAMP) * 100 + MONTH(CURRENT TIMESTAMP)