I would like to get results in my query from a specific time period. What I want to do is run a report on Saturday that will return results from between 7 AM on Monday of the current week to 5 PM on Friday of the current week (working hours).
I was able to do this:
BETWEEN DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7)
AND DATEADD(wk, DATEDIFF(wk, 11, GETDATE()), 11)
However, that only gets the days. How can I add the times?
Thanks in advance!
Update:
I wonder if you could help me one last time. I added that date information to the query, but I am getting results about 5x what I would expect. Let me post the whole code, so you can see what I'm doing:
DECLARE #inc INT, #out INT
SET #inc = (SELECT COUNT(SessionID) FROM altigen.dbo.CDRMAIN WHERE
DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 9, GETDATE()), 9)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 9, GETDATE()), 9))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 10, GETDATE()), 10)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 10, GETDATE()), 10))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 11, GETDATE()), 11)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 11, GETDATE()), 11))
AND Direction = 1 AND VMDuration = 0 AND TargetWGNum IN ('200','201','210','211','212','240'))
SET #out = (SELECT COUNT(SessionID) FROM altigen.dbo.CDRMAIN WHERE
DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 9, GETDATE()), 9)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 9, GETDATE()), 9))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 10, GETDATE()), 10)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 10, GETDATE()), 10))
OR DATEADD(ss, CAST((StartTime - 28800) AS INT), '1970-01-01') BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 11, GETDATE()), 11)) AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 11, GETDATE()), 11))
AND Direction = 2 AND VMDuration = 0 AND TargetWGNum = 0 AND LEN(TargetNum) > 3)
SELECT #inc + #out AS TotalCalls
Basically, this is querying a call database to get the total number of incoming and outgoing calls between working hours, Mon-Fri.
Target = 1/2 means incoming/outgoing, respectively
TargetWGNum indicates the workgroup for the call, and should be within the list for incoming, or 0 for outgoing
VMDuration = 0 means no voicemail was left
The length of the target number means it wasn't to a three-digit extension (outgoing)
The StartTime is store in epoch time, so I'm casting it as an integer before calculating.
Maybe there's a simpler, better way to do it, or just something I'm overlooking? For this week, I'm expecting a few hundred calls, and I'm getting nearly 2,000 as the result for that query.
Thanks!
Just add hours:
BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7))
AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 11, GETDATE()), 11))
If you need to get results within working hours for each day you need to set the time ranges separately:
myDate BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7))
AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7)) OR
myDate BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8))
AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8)) OR
myDate BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 9, GETDATE()), 9))
AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8)) etc.
Update: if you have other conditions that follows the date/time condition in your WHERE clause do not forget to enclose the conditions with OR operator into brackets:
WHERE
(myDate BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7))
AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 7, GETDATE()), 7)) OR
myDate BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8))
AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8)) OR
myDate BETWEEN DATEADD(hh, 7, DATEADD(wk, DATEDIFF(wk, 9, GETDATE()), 9))
AND DATEADD(hh, 17, DATEADD(wk, DATEDIFF(wk, 8, GETDATE()), 8)) etc.
) AND Direction = 1 AND VMDuration = 0 AND ... etc.
Read about SQL Server operator precedence here for more information
Related
I'm using the following code to get the date of every day in the current week, in SQL Server:
SELECT
DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0) Monday,
DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0) + 1 Tuesday,
DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0) + 2 Wednsday,
DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0) + 3 Thursday,
DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0) + 4 Friday,
DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0) + 5 Saturday,
DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0) + 6 Sunday;
I'm using this query to fill a bar chart in a asp.net application.
I need the same thing but with the months of the current year.
Can you help me with this, please?
Edit: More like a query to retrieve data from every month of this year.
This will return the first and last day of every month for the current year.
select FirstDay = dateadd(month, thisMonth - 1, dateadd(year, datediff(year, 0, getdate()), 0))
, LastDay = dateadd(day, -1, dateadd(month, thisMonth, dateadd(year, datediff(year, 0, getdate()), 0)))
from
(
values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)
) x(thisMonth)
In SQL server, I'd like to display the date and time period for my reporting. The time period in the WHERE clause is below:
WHERE EventDate >= dateadd(wk, datediff(wk, 0, getdate()) -5, 0)
AND EventDate <= dateadd(wk, datediff(wk, 0, getdate()), 0)
how can I display this in the format: "26 Mar 2017 - 13 Apr 2017"
If I understand your question correctly, you want the period from 5 weeks ago to 5 weeks in the future.
You could try the following:
-- etc
WHERE EventDate BETWEEN dateadd(week,-5,getdate()) AND dateadd(week,5,getdate());
If you want to display the dates, you can try this:
SELECT format(dateadd(week,-5,getdate()),'d MMM yyyy') +' - '+ format(dateadd(week,5,getdate()),'d MMM yyyy');
If all you want to do is see the dates, just use select:
select dateadd(wk, datediff(wk, 0, getdate()) -5, 0)
, dateadd(wk, datediff(wk, 0, getdate()), 0)
If you want to see the format: "26 Mar 2017 - 13 Apr 2017":
select cast(dateadd(wk, datediff(wk, 0, getdate()) -5, 0) as varchar(20)) +
' - ' +
cast(dateadd(wk, datediff(wk, 0, getdate()), 0) as varchar(20))
I have a date field and i need to display the week of the date field in select statement,
Eg : if the date is '2014-09-15 00:00:00', i need to display as '2014-09-14 to 2014-09-20 ' which is start day to end day of the week
I have tried using
Select dateadd(week, datediff(week, 0, getdate()), -1)+' to ' +DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7)
But it is giving me conversion failure,how can i write the above to display in sql
Both of these expressions
dateadd(week, datediff(week, 0, getdate()), -1)
and
DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7)
returns a Datetime value and ' to ' is a string value.
You will need to convert your datetime values to a string to concatenate these values together.
SELECT CONVERT(VARCHAR(23), dateadd(week, datediff(week, 0, getdate()), -1), 121)
+ ' to ' +
CONVERT(VARCHAR(23), DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7), 121)
RESULT: 2014-09-14 00:00:00.000 to 2014-09-21 00:00:00.000
you have to cast you statement
like this
SELECT CONVERT(VARCHAR(10), dateadd(week, datediff(week, 0, getdate()), -1), 25) + ' to ' + CONVERT(VARCHAR(10), DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 7), 25)
I am working in SQL Server 2008. I am writing a stored procedure which aggregates data on a weekly basis.
Code for aggregation is
ALTER PROCEDURE [dbo].[ups_URLBatchStats]
(#startDate datetime, #endDate datetime,#source varchar(8))
AS BEGIN
SELECT
DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6) AS [Week Commencing],
SUM(Unresolved) AS Unresolved,
SUM(Resolved) AS Resolved,
SUM(TurkSpend) AS TurkSpend
FROM
dbo.V_URLBatchStats
WHERE
ScheduleDate BETWEEN #startDate AND #endDate
AND Source = ISNULL(#source, Source)
GROUP BY
DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6)
ORDER BY
DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6)
END
Show it gives me correct result, but if there are no data for any week I have to show it with values of '0' in the columns.
So how can I handled these skipped weekly rows?
Thanks in advance.
It seems like you are currently selecting the wrong week, I tried to fix this:
SELECT dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, #startdate)-1, 6)) AS [Week Commencing],
coalesce(SUM(Unresolved), 0) AS Unresolved,
coalesce(sum(Resolved), 0)as Resolved,
coalesce(sum(TurkSpend), 0) as TurkSpend
FROM dbo.V_URLBatchStats
right join
master..spt_values
on ScheduleDate between #startDate and #endDate and Source=ISNULL(#source,Source)
where type = 'P' and dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, #startdate)-1, 6)) <= #enddate
GROUP BY dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, #startdate)-1, 6))
ORDER BY dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, #startdate)-1, 6))
You can RIGHT JOIN your week column with sysobjects with a row number generated:
SELECT o.Num AS [Week Commencing], SUM(Unresolved) AS Unresolved,sum(Resolved)as Resolved,sum(TurkSpend) as TurkSpend
FROM dbo.V_URLBatchStats s
RIGHT JOIN (SELECT ROW_NUMBER() OVER (ORDER BY object_id) as [Num] FROM sysobjects) o
on DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6) = o.Num
WHERE ScheduleDate between #startDate and #endDate
AND Source=ISNULL(#source,Source)
GROUP BY DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6), o.Num
ORDER BY 1
Note this is written from memory and untested, but the principle should work.
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