DateAdd - SQL expression - sql

I am trying to create an expression with SQL. The expression value is trying to assign a value to the days of the week. Sunday is 1 through to Saturday which is 7. I am then trying to add 5 days if it is a Monday so that it lands on a Friday otherwise every other day add 7 days. E.g.
WeekDay Inlist("2",",") DateAdd(5, "d") OR ds WeekDay Inlist("1,3,4,5,6,7",",") DateAdd(7, "d")
However this does not seem to work?
So basically I enter my date in a databox as 15/03/2017 which is a Wednesday,
Our expression would say if its a Monday to add 5 days and therefore result in false. Because its a Wednesday we would need to say add 7 days, this ignores Saturday and Sunday and therefore would result in True. This would land on the following Wednesday.
Any ideas? :D

Not sure which variation of SQL you're using, but there's likely an equivalent to the T-SQL CHOOSE() and DATEPART() functions in most variants that will do this.
The expression syntax could end up something like this:
DATEADD(CHOOSE(DATEPART("dw", date), 7, 5, 7, 7, 7, 7, 7), "d", date)

Related

How to create a SQL date range query where the date range depends on holidays and weekends?

I would like fetch all records in Postgres that match a particular date range. The column 'date' is of type Date.
Return all rows where date is tomorrow's date
If today is a Friday, fetch rows that are Saturday, Sunday and Monday
If Monday is a holiday (ex: July 4), on Friday (7/1), we will fetch transactions for Saturday (7/2), Sunday (7/3), Monday (7/4) and Tuesday (7/5)
There may be multiple holidays in tandem and the logic needs to take that into account. Assume the holidays are all available as an array of dates.
My current solution is to blindly fetch all rows that match tomorrow, and then using code (the app is Ruby on Rails) perform the above logic and look ahead if necessary.
Is there an elegant SQL solution to the above problem?
If you are able to create array of dates to fetch in ruby, as you should be you are doing that already right now to figure out if you need to fetch anything else after tomorrow, you should be able to call something like this:
array_of_dates = [Date.new(2022, 4, 30), Date.new(2022, 5, 1), Date.new(2022, 5, 2)]
MyModel.where(date: array_of_dates).order(:date)
That should be enough. It gets translated to SQL like this:
select * from my_models
where date IN ('2022-04-30', '2022-05-01', '2022-05-02')
order by date
Order is not necessary.

Pass column value as Date Part argument

I am trying to generate a string array of weekdays and use it find how many times each day appears in a month
I am using standard sql on BigQuery
My query would look like
with weeks as (select array['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY'] as wk)
select DATE_DIFF('2019-01-31','2019-01-01',WEEK(wk)) AS week_weekday_diff
from weeks, unnest(wk) as wk
The query however fails with the error A valid date part argument for WEEK is required, but found wk. wk is a column value having the Days of Week, WEEK is a Functions which expects a literal DAYOFWEEK. Is there a way i pass the column value as arguments
Below is for BigQuery Standard SQL
error "A valid date part argument for WEEK is required, but found wk"
WEEK(<WEEKDAY>): Valid values for WEEKDAY are literal SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.
... Is there a way i pass the column value as arguments?
If you wish - you can submit feature request at https://issuetracker.google.com/issues/new?component=187149&template=0
find how many times each day appears in a month
To get your expected result and overcome above "issue" you can approach task from opposite angle - just extract weekdays positions and then do needed stats as in example below
#standardSQL
WITH weekdays AS (SELECT ['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY'] AS wk)
SELECT wk[ORDINAL(pos)] weekday, COUNT(1) cnt
FROM weekdays,
UNNEST(GENERATE_DATE_ARRAY('2019-01-01','2019-01-31')) day,
UNNEST([EXTRACT(DAYOFWEEK FROM day)]) pos
GROUP BY pos, weekday
ORDER BY pos
with result
Row weekday cnt
1 SUNDAY 4
2 MONDAY 4
3 TUESDAY 5
4 WEDNESDAY 5
5 THURSDAY 5
6 FRIDAY 4
7 SATURDAY 4
Trying your query, what I have noticed to be returning an error is:
select DATE_DIFF('2019-01-31','2019-01-01',WEEK('WEDNESDAY')) AS week_weekday_diff;
as the function WEEK(< WEEKDAY >) is expecting something like:
select DATE_DIFF('2019-01-31','2019-01-01',WEEK(`WEDNESDAY`)) AS week_weekday_diff;
OR
select DATE_DIFF('2019-01-31','2019-01-01',WEEK(WEDNESDAY)) AS week_weekday_diff;
I think that the WEEK(< WEEKDAY >) only accepts the weekdays in the format exposed here, so no strings should be valid.

Find the Friday after Next in Oracle

I have a weird situation where I need to make a DueDate to be the following Friday.
So if the date is Monday, March 11th 2019 then the DueDate is Friday March 22nd.
I am able to do this easily with:
TRUNC(Next_Day(FilingPeriod, 'FRI')) + 7 as DueDate
My issue comes when the day is Friday March 15th 2019 ad it should also have a DueDate of Friday March 22nd, instead it has a DueDate of Friday March 29th.
And I get why. I have been looking for a way to simplify this or throw in a check to determine if the current date is a Friday and go from there.
I have looked for a bit and read similar questions but I still can not seem to find it.
Thanks for any help
Just subtract 1 from the date before using NEXT_DAY():
TRUNC(Next_Day(FilingPeriod - 1, 'FRI')) + 7 as DueDate
Get back to Monday, the first day of the ISO week. Then go plus 4, then plus 7 days:
TRUNC(FilingPeriod, 'iw') + 11
On a sidenote: I'd avoid NEXT_DAY whenever possible. The day name depends on the current language setting and NEXT_DAY has no parameter to override this. This renders the function rather dangerous, because it makes a query fail-prone.

SQL Server: Count number of records on weekly basis (Week = Thursday to Wednesday)

I need some help in writing an SQL in SQL Server where I need to count number of rows group by weeks. There is a tricky description of week which is following
- For any date before 08/13/2015 the week is of 7 days (i.e. from Thu through Wed)
- For date 08/13/2015 the week is consider a 9 day week (i.e. from Thursday through Friday so its between 08/13/2015 through 08/21/2015)
- For date 08/22/2015 the week is back to 7 days (i.e. Sat through Friday)
Now having said all the above the result I want to see in my report is the following way . NOTE: WE column in the below attached image is the last day of the week for the range.
Sample Result Image
Just write a case statement for the 3 different options. You can find the start day with something like this:
DATEADD(week, DATEDIFF(day, 3,getdate()) / 7, 3) -- Thursdays
DATEADD(week, DATEDIFF(day, 5,getdate()) / 7, 5) -- Saturdays
The numbers 3 and 5 come from the fact that day 0 (=1.1.1900) is Monday.
If you use this a lot, it might be a good idea to write a inline table valued function to return the dates you need.

SSRS expression - get date of most recent saturday

I am trying to find an SSRS expression that will return the date of the most recent Saturday. If the expression runs on a Saturday, I want it to display the Saturday of the previous week.
I toyed around with an example I found online, and got it to produce the value I need it to produce. Listed below:
=IIf(Parameters!O_endDate.Value = nothing, DateAdd("d", -7-(WeekDay(Today(),7))+8, Today()), Parameters!O_endDate.Value)
I apologize for the stupid post. I cannot understand why the above expression is producing the value I need, and I want to know if it will continue to work as I want it to work, when run on other days of the week in the future. Note: I ran this code on a Sunday.
For your purposes, I don't think you need the IIF statement - this just returns the value of the parameter if it is not nothing.
This leaves the key operation as DateAdd("d", -7-(WeekDay(Today(),7))+8, Today()).
What this does is add -7-(WeekDay(Today(),7))+8 days to today - this can be simplified to 1-(WeekDay(Today(),7)) since -7+8=1.
Looking at the documentation here, the return_type appears to be invalid since the function is only defined for values of 1, 2 & 3 - if its working now then it may not continue to work.
This will work all the time DateAdd("d", 1 - WeekDay(Today(), 1), Today()) if you want the most recent Sunday to be today when today is a Sunday or use DateAdd("d", WeekDay(Today(), 2)), Today()) if the most recent Sunday is last week when today is a Sunday.
Note that in both cases this may produce the wrong answer at around midnight due to the 2 calls to Today() a few miliseconds apart. To be absolutely correct it should be:
Declare #DateToCheck datetime=Today()
Select DateAdd('d', 1 - WeekDay(#DateToCheck, 1), #DateToCheck)
This is a more generalised approach that should be closer to ANSI SQL.
See the SQL Fiddle for SQL Server 2008.
Becuase the return value of DATEPART depends on a global database setting, the return value is adjusted for a known Saturday. By changing this to another day of the week you will get the last that day.
You could try this:
=DateAdd("d", -1 * (weekday(today()) mod 7 ), today())