用于获取上个月任何数据的SQL

时间:2013-06-28 10:23:05

标签: sql sql-server sql-server-2008

嗨我仍然是相当新的SQL脚本,我已经在下面写了一些内容,以获取我希望在任何给定日期运行的所有前几个月数据,无论一个月内的天数

表格日期格式为2013-05-10 00:00:00.000

我只是在专家的眼睛下看脚本,并告知我是否对错,如果我有请的话:

SELECT 
[Circuit Number]
,[Request Number]
,[RequestDate]
FROM [QuoteBase].[dbo].[Requests]
WHERE RequestType LIKE 'Cancel%' 
AND DATEPART(mm, [RequestDate]) = DATEPART(mm, DATEADD(mm, -1, getdate()))
AND DATEPART(yyyy, [RequestDate]) = DATEPART(yyyy, DATEADD(mm, -1, getdate()))

2 个答案:

答案 0 :(得分:1)

SELECT 
    [Circuit Number]
   ,[Request Number]
   ,[RequestDate]
FROM
   [QuoteBase].[dbo].[Requests]
WHERE
   RequestType LIKE 'Cancel%' 
   AND
   [RequestDate] >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0);  --year
   AND
   [RequestDate] >= DATEADD(mm, DATEDIFF(mm, 32, GETDATE()), 0);   -- start last month
   AND
   [RequestDate] < DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0);   -- start this month

这使用该技术来找到月份的开头:Need to calculate by rounded time or date figure in sql server

另外,不要在谓词上使用函数。请参见此处的第2项:http://www.simple-talk.com/sql/t-sql-programming/ten-common-sql-programming-mistakes/

在这种情况下,像这样的索引将是有用的

CREATE INDEX IX_Whatever ON
         QuoteBase (RequestDate, RequestType)
            INCLUDE ([Circuit Number], [Request Number])

答案 1 :(得分:1)

我不是SQL专家,但试试这个:

SELECT [Circuit Number]
,[Request Number]
,[RequestDate]
FROM Requests
WHERE RequestType LIKE 'Cancel%'
AND DATEDIFF(mm,Requestdate , GETDATE())=1
AND DATEDIFF(yy,Requestdate, GETDATE())=0

查看我的Fiddle Demo

说明:

DATEDIFF(mm,Requestdate , GETDATE())=1 (Only Request previous Month of the Current Date)

下一个条件:

DATEDIFF(yy,Requestdate, GETDATE())=0 (Only in same year as Current Date)

但是,如果您只想上个月,无论是否与当前日期相同,那么您可以删除第二个条件,例如:

SELECT [Circuit Number]
,[Request Number]
,[RequestDate]
FROM Requests
WHERE RequestType LIKE 'Cancel%'
AND DATEDIFF(mm,Requestdate , GETDATE())=1

请参阅Demo

例如,如果CurrentDate为2013-01-19,则会包含任何December 2012请求,尽管它不是同一年,但显然是上个月。