簡體   English   中英

如何在WHERE子句中使用日期范圍

[英]How to use Date range in the WHERE clause

我想在下面的SQL Server Query中修改我的Where子句,以便它將選擇上個月的所有記錄。

示例:如果我在2月20日運行查詢,則應提取1月1日至1月31日的數據

我嘗試使用以下內容,但您可能會注意到,它從執行之日起一個月后便獲取了記錄。

WHERE date_col >= cast(dateadd(Month, -1, getdate()) as date) and
      date_col <= cast(getdate() as date)

我並不是說這是最好的方法,但是它應該可以工作:

SELECT * from YourTable
WHERE  DATEPART(Month, date_col) = (DATEPART(Month,GETDATE()) - 1)
AND    DATEPART(Year, date_col) = DATEPART(Year,DATEADD(Month, -1, GETDATE()))

SQL Server 2012及更高版本

在這種情況下,EOMONTH看起來可能是有用的功能。 EOMONTH(getdate(),-1)是上個月底。 EOMONTH(getdate(),-2)是前一個月的月底。

嘗試類似

WHERE date_col >= cast(EOMONTH(getdate(), -1) as date) and date_col <=
cast(EOMONTH(getdate(),-2) as date);

要獲得上個月的最后一天和第一天:

SELECT DATEADD(month, DATEDIFF(month, 0, DATEADD(MONTH,-1,GETDATE())), 0) AS First_Day_Of_Last_Month
       ,DATEADD(s,-1,DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()),0))       AS Last_day_Of_Last_Month

結果:

╔═════════════════════════╦═════════════════════════╗
║ First_Day_Of_Last_Month ║ Last_day_Of_Last_Month  ║
╠═════════════════════════╬═════════════════════════╣
║ 2014-05-01 00:00:00.000 ║ 2014-05-31 23:59:59.000 ║
╚═════════════════════════╩═════════════════════════╝

您的查詢

WHERE date_col >= DATEADD(month, DATEDIFF(month, 0, DATEADD(MONTH,-1,GETDATE())), 0)
  AND date_col <= DATEADD(s,-1,DATEADD(MONTH, DATEDIFF(MONTH,0,GETDATE()),0))

由於需要上個月的所有記錄,因此可以只比較當前日期和date_col值的月份和年份部分,如下所示:

select * 
from yourtable
where 
(month(date_col) = month(getdate()) - 1
and year(date_col) = year(getdate()) 
and month(getdate()) <> 1)
or
(month(date_col) = 12
 and year(date_col) = year(getdate()) - 1
 and month(getdate()) = 1)

該查詢也已被某個人問過,並且答案也不錯。

SELECT * 
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))

在SQL Server中獲取上個月的記錄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM