[英]SQL - how to get data from previous month
我正在使用sql server2008。我想從上個月到查詢運行的那一刻獲取所有數據(在“ where”子句中)。 例如,如果今天是2014年4月1日,它將收集2014年1月1日至2014年1月31日之間的所有信息
這是一個簡單的方法:
where year(datecol) * 12 + month(datecol) = year(getdate()) * 12 + month(datecol) - 1
此表達式不是“可保留的”,表示查詢無法利用索引。 如果您有一個大表並且這很重要,則可以執行日期算術:
where datecol >= dateadd(month, -1, cast( (getdate() - datepart(day, getdate()) + 1) as date)) and
datecol < cast( (getdate() - datepart(day, getdate()) + 1) as date)
解決問題的原因:
DATEPART(m,date_created)= DATEPART(m,DATEADD(m,-1,getdate()))和DATEPART(yyyy,date_created)= DATEPART(yyyy,DATEADD(m,-1,getdate()))
不要嘗試使用本月的最后一天,像這樣使用“下個月的第一天”既容易又可靠(請注意使用小於):
select
*
from tables
where (
dateField >= "1st of this Month"
and
dateField < "1st of Next Month"
(
計算:
SELECT
GETDATE()
AS "getdate with time"
, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
AS "getdate time truncated"
, DATEADD(dd, -(DAY(GETDATE()) - 1), DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
AS "day 1 this month"
, DATEADD(MONTH, 1, DATEADD(dd, -(DAY(GETDATE()) - 1), DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)))
AS "day 1 next month"
;
所以:
select
*
from tables
where (
dateField >= DATEADD(dd, - (DAY(getdate()) - 1), DATEADD(dd, DATEDIFF(dd,0, getDate()), 0)) -- "1st of this Month"
and
dateField < DATEADD(month,1,DATEADD(dd, - (DAY(getdate()) - 1), DATEADD(dd, DATEDIFF(dd,0, getDate()), 0))) -- "1st of Next Month"
(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.