Comparing only Year and Month

泄露秘密 提交于 2019-12-11 14:54:34

问题


I'm using this to compare Year and month, but it failing when month is less than current month even though the year is greater than current year

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

回答1:


You could add and extra condition to match the situation when the YEAR is equal..

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))

UPDATE

As @Clockwork-Muse said, an alternative approach that may yield better performance would be to get the beginning of the current month and compare against that:

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



回答2:


try this

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


来源:https://stackoverflow.com/questions/22414360/comparing-only-year-and-month

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