SQL Server 2005 select fields from a certain time frame - sql-server-2005

Right now I'm using this command to retrieve all fields from the current day:
SELECT COUNT(*)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
AND
DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
However, I want to be able to get the fields that were entered between noon yesterday and noon today - how can I go about doing that?

0.5 is noon (eg half a day)
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), -0.5)
AND
DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0.5)

DECLARE #NoonToday DATETIME;
SET #NoonToday = DATEADD(HOUR, 12, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP));
SELECT COUNT(*) FROM [SecureOrders]
WHERE [DateTime] >= DATEADD(DAY, -1, #NoonToday)
AND [DateTime] < #NoonToday;

it might seem ugly but should work
SELECT
COUNT(*)
FROM
[SecureOrders]
WHERE
DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) - 0.5 AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1) + 0.5

A variation on #Aaron Bertrand's solution, without declaring a variable and without treating a non-zero integer value as a date:
SELECT COUNT(*)
FROM SecureOrders o
CROSS JOIN (
SELECT DATEADD(HOUR, DATEDIFF(DAY, 0, GETDATE()) * 24 + 12, 0)
) AS d (TodayNoon)
WHERE o.DateTime < d.TodayNoon
AND o.DateTime >= DATEADD(DAY, -1, d.TodayNoon)

Related

SQL Last Three Months

I have wrote SQL to select user data for last three months, but I think at the moment it updates daily.
I want to change it so that as it is now October it will not count Octobers data but instead July's to September data and change to August to October when we move in to November
This is the SQL I got at the moment:
declare #Today datetime
declare #Category varchar(40)
set #Today = dbo.udf_DateOnly(GETDATE())
set #Category = 'Doctors active last three months updated'
declare #last3monthsnew datetime
set #last3monthsnew=dateadd(m,-3,dbo.udf_DateOnly(GETDATE()))
delete from LiveStatus_tbl where Category = #Category
select #Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
WHERE LastLoggedIn >= #last3monthsnew
How would I edit this to do that?
WHERE LastLoggedIn >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-3, 0)
AND LastLoggedIn < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
The above statement will return any results in July till before the start of current month.
Referencing this answer to get the first day of the month:
How can I select the first day of a month in SQL?
You can detect the month limitations like so:
select DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0) AS StartOfMonth
select DATEADD(month, DATEDIFF(month, 0, getdate()), 0) AS EndMonth
Then you can add that into variables or directly into your WHERE clause:
declare #StartDate datetime
declare #EndDate datetime
set #StartDate = DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0)
set #EndDate = DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
select #Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
where LastLoggedIn >= #StartDate AND LastLoggedIn < #EndDate
Or:
select #Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
where LastLoggedIn >= DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0)
and LastLoggedIn < DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
How about using BETWEEN ?
WHERE LastLoggedIn
BETWEEN
DATEADD(month, DATEDIFF(month, 0, GETDATE())-3, 0)
AND
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)

MS SQL Convert date to short

I am trying to get all of the records from a table where the ExpiryDate field is exactly one month away.
The problem however is that the ExpiryDate is stored with the hours, minutes and seconds. How do I therefore say - Get me all of the records from my table where the ExpiryDate (dd/MM/yyyy) is one month ahead of now (dd/MM/yyyy).
This is what I have currently:
SELECT * FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE mt.ExpiryDate = DATEADD(MONTH, 1, GETDATE())
AND mt.IsComplete = 1;
You need some buffertime like
SELECT * FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE mt.ExpiryDate < DATEADD(MONTH, 1, GETDATE())
AND mt.ExpiryDate > DATEADD(DAY, -1, DATEADD(MONTH, 1, GETDATE()))
AND mt.IsComplete = 1;
This will get you all recors that have an expiredate between 1 month ahead an (1 month - 1 day) ahead.
SELECT * FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE mt.ExpiryDate >= DATEADD(DAY, DATEDIFF(DAY, 0, DATEADD(MONTH, 1, GETDATE())), 0)
AND mt.ExpiryDate < DATEADD(DAY, DATEDIFF(DAY, 0, DATEADD(MONTH, 1, GETDATE()) + 1), 0)
AND mt.IsComplete = 1;
I didn't make operation on ExpiryDate as it might be used by an index
Try this:
SELECT * FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE convert(varchar, mt.ExpiryDate, 102) = convert(varchar, DATEADD(MONTH, 1, GETDATE()),102)
AND mt.IsComplete = 1;

SQL - Get data based on months form a dateTime column

With SQL Server, I have a column with a launch date (dateTime). I want to report on everything that is being launched between all of last month (from viewing date) thru all of this month and next month.
So basically a full 3 month period.
What is the best way to write that?
Are you looking for something like this?
DECLARE
#StartDate DATETIME,
#EndDate DATETIME
SELECT
#StartDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0),
#EndDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0)
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0), -- beginning of this month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0), -- beginning of last month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 1, 0) -- beginning of next month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0) -- beginning of two months from now
SELECT
*
FROM
[Table]
WHERE
[LaunchDate] >= #StartDate
AND [LaunchDate] < #EndDate
This will give you all the results starting from the beginning of the previous month and before the beginning of two months from now (a full 3 month range)
Maybe something like SELECT /*what_you_want*/ from launches WHERE lauchDate BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101') AND DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) + 2, '19000101')
SELECT Foo
FROM Bar
WHERE LaunchDate >= DATEADD(mm, -1, GETDATE())
AND LaunchDate <= DATEADD(mm, 1, GETDATE())

How to get the last month data and month to date data

Need help in writing the query to get the last month data as well as month to date data.
If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011).
If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011.
Thanks,
Shahsra
Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
so most likely
WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Step back one month, subtract the number of days to the current date, and add one day.
WHERE
DateField <= GetDate() AND
DateField >= DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)
To remove the time quickly, you can use this
Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )
So the second part would be (without time)
DateField >= Cast( Floor( Cast( (DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)) AS FLOAT ) ) AS DATETIME )
Select Column1, Column2 From Table1
Where DateColumn <= GetDate() AND
DateColumn >= DATEADD(dd, - (DAY(DATEADD(mm, 1, GetDate())) - 1), DATEADD(mm, - 1, GetDate()))
Edit: +1 to Russel Steen. I was posting mine before I knew he had posted.
Very helpful page
declare #d datetime = '2011-04-03';
declare #startDate datetime;
select #startDate =
CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,#d),113),8) AS datetime);
select #startDate;

GETDATE last month

I am trying to list last a website's statistics.
I listed Last 30 days with;
CONVERT(VARCHAR(10), S.DATEENTERED, 101)
BETWEEN
CONVERT(VARCHAR(10), GETDATE()-30, 101)
AND
CONVERT(VARCHAR(10), GETDATE(), 101)
and this month with;
RIGHT(CONVERT(VARCHAR(10), S.DATEENTERED, 103), 7) =
RIGHT(CONVERT(VARCHAR(10), GETDATE(), 103), 7)
but I have no idea what query to use for last month. I tried with;
RIGHT(CONVERT(VARCHAR(10), S.DATEENTERED, 103), 7) =
RIGHT(CONVERT(VARCHAR(10), GETDATE()-1, 103), 7)
Did not work.
Dates are always a joy to work with in any programming language, SQL not excluded.
To answer your question to find all records that occurred last month
select S.DATEENTERED
,*
from sometable S
where S.DATEENTERED
between dateadd(mm, datediff(mm, 0, dateadd(MM, -1, getdate())), 0)
and dateadd(ms, -3, dateadd(mm, datediff(mm, 0, dateadd(MM, -1, getdate())) + 1, 0))
order by 1
To expand the best means for getting records within a certain time-frame is by utilizing the datediff function, dateadd function, and the between condition in the where clause.
select 'howdy'
,getdate()
where getdate()
between dateadd(mm, 0, 0)
and dateadd(ms, -3, dateadd(mm, datediff(mm, 0, dateadd(mm,-1,getutcdate())) + 1, 0))
The above code will result in no records returned because it is checking to see if today's date is between 1900-01-01 00:00:00.000 and the last possible recorded date of last month (the last day and 23:59:59.997 - SQL Server DATETIME columns have at most a 3 millisecond resolution).
The following code will return a record as the date we are searching for is one month ago.
select 'howdy'
,dateadd(mm, -1, getdate())
where dateadd(mm, -1, getdate())
between dateadd(mm, 0, 0)
and dateadd(ms, -3, dateadd(mm, datediff(mm, 0, dateadd(mm,-1,getutcdate())) + 1, 0))
A break down of the where clause:
WHERE getdate() -- date to check
between dateadd(mm, 0, 0) -- begin date
and dateadd(ms, -3, dateadd(mm, datediff(mm, 0, dateadd(mm,-1,getutcdate())) + 1, 0)) -- end date
Finally, a variety of dates can be ascertained in this manner here is a pretty complete list:
select dateadd(mm, 0, 0) as BeginningOfTime
,dateadd(dd, datediff(dd, 0, getdate()), 0) as Today
,dateadd(wk, datediff(wk, 0, getdate()), 0) as ThisWeekStart
,dateadd(mm, datediff(mm, 0, getdate()), 0) as ThisMonthStart
,dateadd(qq, datediff(qq, 0, getdate()), 0) as ThisQuarterStart
,dateadd(yy, datediff(yy, 0, getdate()), 0) as ThisYearStart
,dateadd(dd, datediff(dd, 0, getdate()) + 1, 0) as Tomorrow
,dateadd(wk, datediff(wk, 0, getdate()) + 1, 0) as NextWeekStart
,dateadd(mm, datediff(mm, 0, getdate()) + 1, 0) as NextMonthStart
,dateadd(qq, datediff(qq, 0, getdate()) + 1, 0) as NextQuarterStart
,dateadd(yy, datediff(yy, 0, getdate()) + 1, 0) as NextYearStart
,dateadd(ms, -3, dateadd(dd, datediff(dd, 0, getdate()) + 1, 0)) as TodayEnd
,dateadd(ms, -3, dateadd(wk, datediff(wk, 0, getdate()) + 1, 0)) as ThisWeekEnd
,dateadd(ms, -3, dateadd(mm, datediff(mm, 0, getdate()) + 1, 0)) as ThisMonthEnd
,dateadd(ms, -3, dateadd(qq, datediff(qq, 0, getdate()) + 1, 0)) as ThisQuarterEnd
,dateadd(ms, -3, dateadd(yy, datediff(yy, 0, getdate()) + 1, 0)) as ThisYearEnd
Using the above list a range of any type can be determined.
The following will find you the start of the last month:
-- Start of last month
SELECT CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,GETDATE()),113),8) AS datetime)
You would then find the start of this month, using the following, minus one.
-- Start of the month
SELECT CAST('01 '+ RIGHT(CONVERT(CHAR(11),GETDATE(),113),8) AS datetime)
When I have to work with dates in SQL Server I often reference Robyn Page's SQL Server DATE/TIME Workbench. The workbench (tutorial) is well laid out and contains just about everything I have ever needed when working with dates on SQL Server.
How about this?
select DATEADD(month, -1, GETDATE())
I would suggest using the first day of last month and the first day of the current month for the operation and rather than using BETWEEN use >= and <. That's my personal opinion, but I believe you will find there are performance and maintainability benefits to this approach.
Here's the sql. You will notice I've included the last day of the last month value just in case you end up going with another approach.
Keep in mind, these dates are based off of 12:00AM that day. In other words, getting values between 6/1/2009 and 6/30/2009 won't get you what you want as all of 6/30/2009 is excluded. If you use the first day of July (7/1/2009) you are covered.
Again, I recommend avoiding BETWEEN all together as shown below. Best of luck.
Declare #LastMonthFirstDay datetime
Declare #LastMonthLastDay datetime
Declare #ThisMonthFirstDay datetime
Set #LastMonthFirstDay = DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - 1, 0);
Set #ThisMonthFirstDay = DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0);
Set #LastMonthLastDay = DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0));
Select * From Table
Where DateEntered >= #LastMonthFirstDay
And DateEntered < #ThisMonthFirstDay;
Try using the DATEADD function. You can add a -1 with the MONTH (mm) datepart and it should work. Here is a link
where year(S.DATEENTERED) = year(dateadd(mm, -1, getdate())) and month(S.DATEENTERED) = month(dateadd(mm, -1, getdate()))
Might not be good performance-wise but you've got the idea.
GET FIRST DAY OF LAST MONTH
SELECT DATEADD(MM, DATEDIFF(MM, '01/01/2000', DATEADD(MM, -1,GETDATE())), '01/01/2000')
GET LAST DAY OF LAST MONTH
SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,'01/01/2000',GETDATE()),'01/01/2000'))
Then search based on this range.
Try:
declare #lastm int
set #lastm = datepart(mm,getdate()) - 1
...
where datepart(mm,s.dateentered) = #lastm