Select 在当前月份的特定日期和上个月之间
Select between a specific day of current month and previous month
我一直在搜索这个,但只得到指定日期的答案。
我面临的问题是:
Return上月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
最后一个可以,但不会 return 当前月份的任何结果。
我已经尝试了几个 where 子句,但似乎只指定日期就可以了。有没有办法动态地做到这一点?
谢谢
您可以使用 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
)
截止到 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)) )
成功了。
谢谢
我一直在搜索这个,但只得到指定日期的答案。
我面临的问题是:
Return上月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
最后一个可以,但不会 return 当前月份的任何结果。
我已经尝试了几个 where 子句,但似乎只指定日期就可以了。有没有办法动态地做到这一点?
谢谢
您可以使用 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
)
截止到 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)) )
成功了。
谢谢