SQL 选择上个月sql中的所有日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21093502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:42:56  来源:igfitidea点击:

Select all where date in Last month sql

sqlsql-servertsql

提问by user3190075

How can I get last month date like

我怎样才能得到上个月的日期

select * from table where date in ( last month  )

I dont want the last 30 days AND how can I get last month automatically

我不想要过去 30 天以及如何自动获得上个月

采纳答案by M.Ali

Edit

编辑

if you mean last month from today. or previous month from a specific date then you need to do something like this

如果你的意思是从今天开始的上个月。或从特定日期开始的上个月然后你需要做这样的事情

SELECT DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))

Or to get records from previous month of the year you can do something like this

或者要获取一年中上个月的记录,您可以执行以下操作

SELECT * FROM Table
WHERE  MONTH(Date) =  DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))
AND YEAR(Date) =    DATEPART(YEAR, DATEADD(MONTH, -1, [Date]))    --<-- or pass year for which year you are checking 

To make your aquery SARGable(Suggested by t-clausen.dk)

使您的查询成为可搜索的(由 t-clausen.dk 推荐)

select * from table 
where date >=dateadd(m, datediff(m, 0, current_timestamp)-1, 0) 
and date < dateadd(m, datediff(m, 0, current_timestamp)-1, 0)

Read here more about sargable Querieswhen working with date/datetime datatypes.

在此处阅读有关使用日期/日期时间数据类型时的sargable 查询的更多信息

回答by Cav

select * from table
where month(date)=month(getdate())-1

回答by Trinity

You can use this

你可以用这个

Select * from table where date between @startdate and @enddate

Or

或者

SELECT * FROM DATE_SAMPLE WHERE 
DATEPART(YEAR, SAMPLE_DATE) = '2013' AND 
DATEPART(MONTH,SAMPLE_DATE) = '01' AND 
DATEPART(DAY, SAMPLE_DATE) = '01'

Is it usefull for you?

对你有用吗?

回答by Obsidian Phoenix

Assuming you want all items where the date is within the last monthi.e. between today and 30/31 days ago:

假设您想要日期在上个月内的所有项目,即今天和 30/31 天前之间:

Select *
From Table
Where Date Between DATEADD(m, -1, GETDATE()) and GETDATE()

回答by XcisioN

You can try to use the between statement to get the specific dates:

您可以尝试使用 between 语句来获取特定日期:

Select * from table where date between '01-01-2014' and '14-01-2014'