对于此类比较,我喜欢将日期时间转换为“从零开始的月份”。你,你可以用算术来计算。
对于您的查询,这看起来像:
select t.*, year(compdate), month(compdate)
from t cross join
(select date('2013-07-01') as compdate) const
where year(compdate)*12+month(compdate) between year(dtBeg)*12 + month(dtBeg) and
year(dtEnd)*12 + month(dtEnd);
在这里,我将 放入compdate
子查询中。这样,如果要检查多个月,只需向表中添加行:
select t.*, year(compdate), month(compdate)
from t cross join
(select date('2013-07-01') as compdate union all
select date('2013-08-01')
) const
where year(compdate)*12+month(compdate) between year(dtBeg)*12 + month(dtBeg) and
year(dtEnd)*12 + month(dtEnd);
这种形式适用于许多 SQL 方言。您可以使用date_format()
.
select t.*, year(compdate), month(compdate)
from t cross join
(select '2013-07' as compdate union all
select '2013-08'
) const
where compdate between date_format(dtBeg, '%Y-%m') and date_format(dtEnd, '%Y-%m)