I need some guidance in getting value from the database within a week time period. I've figured out how to use DATEPART where I can do DATEPART(wk, date_value) = DATEPART(datepart, GETDATE()) but what I can't figure out is how to do a specific day of the week. Like I only want to retrieve information from this Tuesday to next Tuesday. Can anyone offer anyone offer any guidance?
Thanks!
In SQL Server, you can do something like this:
Set DateFirst 1;
Select DateAdd(d, -DatePart(dw, CURRENT_TIMESTAMP) + 3
, CURRENT_TIMESTAMP) As ThisWeekTuesday
, DateAdd(d, 7, DateAdd(d, -DatePart(dw, CURRENT_TIMESTAMP) + 3
, CURRENT_TIMESTAMP)) As TuesdayAfterThat
In MIcrosoft Access, you would do something like:
Select DateAdd("d", -DatePart("w", Now()) + 3, Now()) As ThisWeekTuesday
, DateAdd("d", 7, DateAdd("d", -DatePart("w", Now()) + 3
, Now())) As TuesdayAfterThat
I recommend creating a Dates table - store one record per day, with fields for SQLDate, DateAsText, Year, Month, MonthAsText, DayOfWeek, DayOfWeekAsText, etc. Then you can query like this:
SELECT
MIN(SQLDate)
FROM
Dates
WHERE
SQLDate > SYSDATETIME()
AND DayOfWeekText = 'Tuesday'
If you'd rather not go through that right now, you can also use DATEPART() and DATEADD(). For the next coming Tuesday, I believe this would be:
DECLARE #TodaysDayOfWeek = DATEPART(DW, SYSDATETIME())
SELECT
CASE WHEN #TodaysDayOfWeek < 3 DATEADD( 3 - #TodaysDayOfWeek, SYSDATETIME())
ELSE DATEADD(10 - #TodaysDayOfWeek, SYSDATETIME() END
I don't have MS SQL handy to confirm this, but it should work if DW starts at 1 for Sunday and ends with 7 for Saturday (this can vary depending on your config). Note that, if called on a Tuesday it will give next Tuesday, not today; to reverse this behavior, change "< 3" to "<= 3".
Related
I am building an SQL view which shows me all entries of table T where the information is last month. I want it so that if I run the view any time in August, it will show me all entries for July, not just a month before which is what I have done with my current code.
Please see this:
where cast(t.Ticket_OpenDate as date) >= cast(dateadd(month, -1, getdate()) as date)
I look forward to hearing from someone.
Using DATEDIFF as in the other answer will not perform well because it cannot use indexes (it is not sarge-able).
It is much better to use a date interval (start and end), in this case we want a half-open interval (exclusive end date):
WHERE t.Ticket_OpenDate >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) - 1, 1)
AND t.Ticket_OpenDate < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) , 1)
You should be able to use the DATEDIFF() function for that:
WHERE DATEDIFF(month, CAST(t.Ticket_OpenDate as date), GETDATE()) = 1
See db<>fiddle for an example.
I want to know the SQL Server query in which I can get record from the table against the specific day (like Monday OR Tuesday) of current week, OR against the specific day from the last 7 days.
Like I want to get record for 1st day of last 7 days OR Like I want to get record for the Monday OR Tuesday from current week.
By the way I can get specific day of current week through this SQL Server query
//Query
SELECT DATEADD(DD, 0 - DATEPART(DW, GETDATE()), GETDATE()) //Get Sunday
SELECT DATEADD(DD, 1 - DATEPART(DW, GETDATE()), GETDATE()) //Get Monday
SELECT DATEADD(DD, 2 - DATEPART(DW, GETDATE()), GETDATE()) //Get Tuesday
But I want to get record from the table against these days, like so:
Select * from tbl_Sale where date = "Here the specific day's date should be called"
Sorry for the long text but I really need to explain that what I need to do, so please if anyone can do this?
Return only those records where date is in the last 7 days and then further restrict your criteria to just Mondays.
SELECT *
FROM tbl_Sale
WHERE DATEDIFF(DAY, GETDATE(), date) BETWEEN -7 AND 0
AND DATENAME(WEEKDAY, date) = 'Monday'
This would also work.
SELECT *
FROM tbl_Sale
WHERE DATEDIFF(DAY, GETDATE(), date) BETWEEN -7 AND 0
AND DATEPART(WEEKDAY, date) = 2 -- by default 2 is equivalent to Monday
You will find a lot of valuable information reading up on Date and Time Data Types and Functions (Transact-SQL). So by default, DATEPART(WEEKDAY, date) will return 1 for any Sunday, 2 for any Monday, etc. However, you can set the first of the week to be whatever day you want by setting DATEFIRST.
Here is some sample code to show the Weekday Names and Weekday Numbers for a range of dates.
How can I select
The past week
Its corresponding days in the year before
This is needed for a dashboard, I would like to show a chart with results from the past seven days. It displays green if our call-center handles 98% of their phone calls within a certain time-span, red if we go over 98%. As a reference I would like to create a chart below with the corresponding seven days in the year before. This is challenging, because weekdays really influence the workload. That means I can't compare a Tuesday with a Sunday or Monday.
For instance, today is Saturday 21st Dec 2019, I would like to report the following timespans:
2019-12-13 00:00:00 -> 2019-12-20 23:59:59
and
2018-12-14 00:00:00 -> 2018-12-21 23:59:59
I made the following code (used within a select statement):
case when cs.ReachedAt between (getdate() - 7) and getdate() then 1 else 0 end as Is_PastWeek
case when cs.ReachedAt between (convert(datetime, convert(varchar(50), convert(date, dateadd(d, -1, dateadd(wk, -52, getdate())))) + ' 23:59:59')) and (convert(datetime, convert(varchar(50), convert(date, dateadd(d, -8, dateadd(wk, -52, getdate())))) + ' 00:00:00')) then 1 else 0 end as Is_SameWeekLastYear
It works, but isn't perfect. I just select the corresponding weekday in the same week as 52 weeks ago. Which means I sometimes end up selecting a matching weekday, but not the nearest. How can I do this better?
EDIT
To clarify what I mean by "picking the nearest corresponding weekday in the year before", i made the following example:
with cte1 as (
select row_number() over (order by (select 1)) - 1 as incrementor
from master.sys.columns sc1
cross join master.sys.columns sc2
), cte2 as (
select dateadd(day, cte1.incrementor, '2000-01-01') as generated_date
from cte1
where dateadd(day, cte1.incrementor, '2000-01-01') < getdate()
), cte3 as (
select convert(date, generated_date) as generated_date
, convert(date, getdate()) as now_date
from cte2
), cte4 as (
select *
, convert(date, dateadd(YEAR, -1, now_date)) as year_back
from cte3
)
select now_date
, generated_date
from cte4
where 1=1
and datepart(week, year_back) = datepart(week, generated_date)
and datepart(DW, year_back) = datepart(DW, generated_date)
This will result in:
For the grey values, I would rather take the weekday of one week later. That way I pick "the nearest corresponding weekday in the year before".
Please note that the above is an example to show what I mean, my ultimate goal is to start with this date, select the whole week before... And all (if possible) neatly within a where clause.
The expression datepart(week, getdate()) will deliver you the calendar week. With this, you can go further.
This is too long for a comment.
What difference does it make? If you are looking for the past week, just look at the same 7 days from the previous year. In one case the week might start on a Tuesday and in the other on a Wednesday. But in both cases, each weekday occurs once.
The logic would be:
where cs.ReachedAt >= datefromparts(year(getdate() - 7) - 1, month(getdate() - 7), day(getdate() - 7) and
cs.ReachedAt < datefromparts(year(getdate()), month(getdate()), day(getdate()))
The logic for the current year:
where cs.ReachedAt >= convert(date, getdate() - 7) and
cs.ReachedAt < convert(date, getdate())
I'm hoping to find a solution for this to automate a report I have. Basically what I'm trying to accomplish here is grabbing a date (first day of previous month, two years ago through last day of previous month current year).
So the date span if running this month would look like this: between 4/1/2013 and 3/31/2015
I have found code to get the date two years ago but I'm not able to also incorporate the month functions... Any help is very much appreciated!
For year I'm using this:
SELECT CONVERT(VARCHAR(25),DATEADD(year,-2,GETDATE()),101)
First day of previous month 2 years ago:
SELECT CONVERT(DATE,dateadd(day, -1, dateadd(day, 1 - day(GETDATE()), GETDATE())))
Last day of last month:
SELECT CONVERT(DATE,DATEADD(month, DATEDIFF(month, 0, DATEADD(year,-2,GETDATE())), 0))
Then just do whatever logic you need with them
Your where clause can look something like this:
where date >= cast(dateadd(year, -2,
dateadd(month, -1, getdate() - day(getdate()) + 1)
) as date) and
date < cast(getdate() - day(getdate()) + 1 as date)
This makes use of the handy convenience that subtracting/adding a number to a datetime is the same as adding a date. The start date says: get the first day of the month, then subtract one month, then subtract two years. This could have been done as dateadd(month, -25, . . .), but I think separating the logic is clearer.
This gives you two dates you are looking for:
SELECT
CAST((DATEADD(yy, -2, DATEADD(d, -1 * DATEPART(dd, getdate()) + 1 , GETDATE() ))) as date) as yourTwoYearsAgoDate,
CAST((DATEADD(d, -1 * DATEPART(dd, GETDATE()), GETDATE())) as date) as yourEndOfLastMonthDate
Given a reference date (e.g. "today"),
declare #today date = '23 April 2015'
The 1st of the month is computed by subtracting 1 less than the day number of the current month:
select first_of_current_month = dateadd(day,1-day(#today),#today)
The last day of the previous month is day 0 of the current month, so to get the last day of the previous month, just subtract the current day number:
select last_of_previous_month = dateadd(day,-day(#today),#today)
Moving two years back is easy:
select two_years_back = dateadd(year,-2, #today )
Putting it all together, this should do you:
declare #today date = '23 April 2015'
select *
first_day_of_current_month = dateadd(day,1-day(#today),#today),
last_day_of_previous_month = dateadd(day, -day(#today),#today) ,
date_from = dateadd(year,-2, dateadd(day,1-day(#today),#today) ) ,
date_thru = dateadd(day, -day(#today),#today)
yielding the expected results:
first_day_of_current_month: 2015-04-01
last_day_of_previous_month: 2015-03-31
date_from : 2013-04-01
date_thru : 2015-03-31
So you should be able to say something like this:
select *
from foo t
where t.transaction_date between dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and dateadd(day, -day(#today),#today)
If you have to deal with datetime values rather than date, its easier to not use between and say something like this:
declare #today date = current_timestamp -- get the current date without a time component
select *
from foo t
where t.transaction_date >= dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and t.transaction_date < dateadd(year, 0, dateadd(day, -day(#today),#today)
[superfluous addition of 0 years added for clarity]
I have a query (pasted below), and I would like to make it so that people don't need to update the completed date range. I would like for it to automatically just get results from last month. So if it is run in February, for example, it will give me results for all completed items that meet my criteria for January. Can anyone think of a way to do that?
select External_ID__c,
Ewrk_Tracking_Number__c,
PIF_Branch_Name,
Distribution_Branch_Name,
Transaction_Type__C,
submitter_date__c, Completed_Date__C,
COUNT(External_ID__c)
from Business_Solutions_D.dbo.Reporting_SalesForce_AspireBaseData
where PIF_Branch_Code = 977
and Completed_Date__C >= '2015-01-01'
and Completed_Date__C < '2015-02-01'
and Delete_Flag__C = 'FALSE'
group by External_ID__c,
Ewrk_Tracking_Number__c,
PIF_Branch_Name,
Distribution_Branch_Name,
Transaction_Type__C,
submitter_date__c,
Completed_Date__C
There is no "keyword" for last month. You have to put that in your predicates.
Here is an example of how to get some date values for this.
select dateadd(MONTH, datediff(MONTH, 0, GETDATE()), 0) as BeginningOfThisMonth
select dateadd(MONTH, datediff(MONTH, 0, GETDATE()) - 1, 0) as BeginningOfPreviousMonth
If you want to see a number of other date routines here is an excellent blog post with quite a few of them. http://www.sqlservercentral.com/blogs/lynnpettis/2009/03/25/some-common-date-routines/
If you mean the last month prior to this one, you can do it in two steps: first, find the first day of the current month
#firstDayOfThisMonth = DATEADD(day, DAY(GETDATE())-1, GETDATE())
then subtract one month:
#firstDayOfLastMonth = DATEADD(month, -1, #firstDayOfThisMonth)
Then your query would be:
and Completed_Date__C >= #firstDayOfLastMonth
and Completed_Date__C < #firstDayOfThisMonth
Another way would be to query where the difference (in months) between Completed_Date__C and the current date is 1:
and DATEDIFF(Completed_Date__C, GETDATE()) = 1
You can do this with date arithmetic. One trick to get the first date of the month is to subtract the current day of the month from the date and add one day. SQL Server allows you to do this with + and - instead of dateadd(), on a datetime value. Of course, you need to remove the time component as well (using cast( as date)).
The logic looks like this for the current month:
where Completed_Date__C >= cast(getdate() - day(getdate()) + 1 as date) and
Completed_Date__C < dateadd(month, 1, cast(getdate() - day(getdate()) + 1 as date))
And like this for the previous month:
where Completed_Date__C >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
Completed_Date__C < cast(getdate() - day(getdate()) + 1 as date)
This has the nice property that it is a sargeable as your original code, so it will take advantage of an index on the column, if appropriate.
You just need to have it do some date math to calculate it.
--Go to last day of prev month - 'Day' to account for varying month day counts
and Completed_Date__C >= GETDATE() - DATEPART(DAY, GETDATE()) - DATEPART(DAY, GETDATE() - DATEPART(DAY, GETDATE())) + 1
and Completed_Date__C < GETDATE() - DATEPART(DAY, GETDATE()) + 1
When you do additions on DateTimes + integer it assumes it day based addition.