我想在下面的 SQL Server 查询
中修改我的 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 - 如何在 WHERE 子句中使用日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24175255/