2017-04-17 82 views
0

我一直在搜索此内容,但只获得了指定日期的答案。从当前月份和上个月的特定日期之间选择

我现在面临的问题是:

返回所有比上月的20日和本月的20日之间的数据。

select name, data, activity from Table 
where (year(data) = year(getdate()) and month(data) = month(getdate())-1 and day(data) >= 20) and (year(data) = year(getdate()) and month(data) = month(getdate()) and day(data) <= 20) 

select name, data, activity from Table 
where year(data) = year(getdate()) and month(data) >= month(getdate())-1 and day(data) >= 20 

这最后一个会工作,但它不会返回当前月份的任何结果。

我已经尝试了几个where子句,但它只接受指定日期的接缝。有没有办法动态地做到这一点?

感谢

回答

0

可以使用eomonth()来比较个月:

select t.* 
from t 
where (day(data) >= 20 and eomonth(data) = eomonth(dateadd(month, -1, getdate()))) or 
     (day(data) < 20 and eomonth(data) = emonth(getdate())); 

可以在SQL Server 2008中做到这一点,但日期算术有点令人讨厌。一种方法是要减去21天,检查它是否是前一个月:

select t.* 
from t 
where (year(dateadd(day, -21, data)) * 12 + month(dateadd(day, -21, data)) = 
     year(getdate()) * 12 + month(getdate()) - 1 
    ) 
+0

感谢@Gordon,但它接缝该公司正在使用SQL Server 2008,仅2012年来的有没有什么办法来模拟2008年EOMONTH EOMONTH的?谢谢 –

0

由于ofmonth上不存在2008年,我翻译与@Gordon正确答案:

(day(data) >= 20 and CONVERT(DATE, dateadd(mm, datediff(mm,0, data)+1,-1)) = CONVERT(DATE, dateadd(mm, datediff(mm,0, dateadd(month, -1, getdate()))+1,-1))) or 
    (day(data) < 20 and CONVERT(DATE, dateadd(mm, datediff(mm,0, data)+1,-1)) = CONVERT(DATE, dateadd(mm, datediff(mm,0, current_timestamp)+1,-1))) 

和有效。

感谢

相关问题