Power BI - How do you calculate first Day of Week? - sql

So here is my scenario.
If it's 20th week of the Year 2016, I need to know it's 5/8/2016. This is consistent for the rest of week. Same goes for all the week.
Week# WeekDate
29 7/10/2016 0:00
30 7/17/2016 0:00
28 7/3/2016 0:00
31 7/24/2016 0:00
32 7/31/2016 0:00
33 8/7/2016 0:00
34 8/14/2016 0:00

dateadd(DAY,-(datepart(weekday,DATEADD(WEEK,30-1,CAST('2016'||'-1-1' AS DATE)))-1),DATEADD(WEEK,30-1,CAST('2016'||'-1-1' AS DATE)))
This works with Intersystems. You will have to construct your own date with the known year value and replace '30' with the known week value from your table

Thanks for the contribution, I did something like below and it worked. This is keeping Sunday as the first day of week.
If you want to use Monday or Tuesday, add +2, +3 in the WeekNum calculation below.
DATE(SampleTableWithDate.Year],1,1) - WEEKDAY(DATE(SampleTableWithDate.Year,1,1),1) + (WEEKNUM(SampleTableWithDate.Date)-1)*7 + 1
Find the First Date of this Year - First Day of Week This Year + Add Weeks till Date

Related

Timeseries : date time averaging and abnormally detection

I"m dealing with a dataset with 4 week sales data (data will be refreshed every hour) and need to observer for abnormality
I think I'll go with a basic approach, to compare with average numbers and I'm trying to figure out how to best break this down so I can answer some questions below
On average, how many orders received at 9:00 , 15:00 or 16:00 past 30 days
On average, how many orders received at 9:00 every Wednesday (past 4 Wednesdays), at 15:00 every Thursday (past 4 Thursdays),
Not sure how do we go about this (after breaking date/time down to Hour and Weekday columns)
date
order ID
order hour
order weekday
10/07/2022 10:26:12 PM
1111
22
6
10/07/2022 10:27:12 PM
2222
22
6
....
....
....
....
19/07/2022 11:34:19 AM
9998
11
1
19/07/2022 11:34:35 AM
9999
11
1
I would love to get your advice please
Thanks
I've ended up going with a tedious approach.
#get current hour & weekday
now=datetime.datetime.now()
today=datetime.date.today()
current_hour=now.hour
current_weekday=today.weekday()
#create a DF with orders from the same hour & weekday window
same_hour_weekday_df=order_df[(order_df.order_hour==current_hour ) & (order_df.order_weekday==current_weekday) ]
#calculate avg orders generated from the past weeks within the same hour and weekyday timeframe
orders_same_hour_weekday=same_hour_weekday_df['order_created_at'].count()
same_hour_weekday_periods=same_hour_weekday_df['order_week'].nunique()
avg_orders_same_hour_weekday=orders_same_hour_weekday/same_hour_weekday_periods

January 1st = Week 1

The below gives me week numbers where week 1 starts on 1/4/2021
date_trunc('week', transaction_date) as week_number
How can I create a week_number where the week starts on January 1st and counts up 7 days for every week thereafter (for every year)?
And round up/down to 52 weeks at the end of the year?
Code attempted:
This doesn't give me the answer, but I'm thinking something like this might work...
ceil(extract(day from transaction_date)/7) as week_number
Expected Output:
transaction_date
week_number
1/1/2020
1
1/8/2020
2
...
...
12/31/2020
52
1/1/2021
1
1/8/2021
2
...
...
12/27/2021
52
12/28/2021
52
12/29/2021
52
12/30/2021
52
12/31/2021
52
1/1/2022
1
Thanks in advance!
A simple way is to use date arithmetic:
select 1 + (transaction_date - date_trunc('year', transaction_date)) / 7 as year_week
The below gives me week numbers where week 1 starts on 1/4/2021
It is the default behaviour and it is defined that way in ISO.
WEEK_OF_YEAR_POLICY
Type Session — Can be set for Account » User » Session
Description
Specifies how the weeks in a given year are computed.
Values
0: The semantics used are equivalent to the ISO semantics, in which a week belongs to a given year if at least 4 days of that week are in that year.
1: January 1 is included in the first week of the year and December 31 is included in the last week of the year.
Default 0 (i.e. ISO-like behavior)
It could be overrriden on multiple levels. The most granular is on the session level:
ALTER SESSION SET WEEK_OF_YEAR_POLICY = 1;
Then you could use the standard code:
SELECT date_trunc('week', transaction_date) as week_number
FROM ...;

Teradata SQL Week Number - Week 1 starting 1st Jan with weeks aligned to specific day of the week

my first post on here so please be gentle...
I'm trying to create a week number variable in Teradata (SQL) that does the following:
Week 1 always starts on 1st January of the given year
Week numbers increment on the specified day of the week
For example: If Saturday was the specified day of the week:
2019-01-01 would be the start of week 1, 2019, changing to week 2 on 2019-01-05
2020-01-01 would be the start of week 1, 2020, changing to week 2 on 2020-01-04
I have come up wit the following based on an Excel function however it doesn't quite work as expected:
ROUND(((DATE_SPECIFIED - CAST(EXTRACT(YEAR FROM DATE_SPECIFIED) || '-01-01' AS DATE) + 1) - ((DATE_SPECIFIED - DATE '0001-01-06') MOD 7 + 1) + 10) / 7) AS REQUIRED_WEEK
The last digit of the section - DATE '0001-01-06' deals with the specified day of the week, where '0001-01-01' would be Monday.
This works in some cases however for some years, the first week number is showing as 0 where it should be 1, e.g. 1st Jan 2018 / 2019 are fine whereas 1st Jan 2020 is not.
Any ideas to correct this would be gratefully received.
Many thanks,
Mike
You can apply NEXT_DAY for both the specified date and Jan 1st of that year, e.g. for Saturday as week start:
(Next_Day(DATE_SPECIFIED,'SAT') - Next_Day(Trunc(DATE_SPECIFIED,'yyyy'),'SAT')) / 7 +1
Hmmm . . . I'm a bit week on Teradata functions. But the idea is to get the start of the second week. This follows the rule:
Jan 1 weekday (TD) 2nd week
Sunday 1 01-02
Monday 2 01-08
Tuesday 3 01-07
Wednesday 4 01-06
Thursday 5 01-05
Friday 6 01-04
Saturday 7 01-03
I think the following logic calculates this:
select t.*,
(case when td_day_of_week(cast(extract(year from DATE_SPECIFIED) || '-01-01' as date) ) = 1
then cast(extract(year from DATE_SPECIFIED) + '-01-02' as date)
else extract(year from DATE_SPECIFIED) + 10 - cast(td_day_of_week(cast(extract(year from DATE_SPECIFIED) || '-01-01') as date)
from t;
Then do you your week calculate either from the second week or subtract one more week to get when the first week really starts.

Number of Weeks in a Month Vb.Net

Is there any DateTimePicker function to get the number of full weeks in a month?
Im looking for something like:
WeeksInMonth("01/01/2020") = 5
This will be the number of weeks per month manually calculated of this year:
Corrigendum: September has 4 weeks.
EDIT:
If the month starts in the mid of a week it should count as full week. It should also counts as full week if the month ends in the mid of a week.
From Monday to Sunday.
EDIT 2:
By mid week i mean if the week starts in Thursday it considers it as a complete week, because it was 4 days (thursday,friday,saturday and sunday) out of 7.
Same for the end, if the week end in thursday it will count as a complete Week, if the week finish in Monday, Tuesday or Wednesday it wont count because it only has 3 days out of 7.
Im taking in to consideration that my complete week starts in Monday and ends in Sunday.
Ex. January 2020 First complete week is: 30-dec-2019 to 05-jan-2020.
Another Example will be March 2020, Last complete week for me is 23-Mar-2020 to 29-Mar-2020, the 2 remaining days (30,31) would be part of April 1st complete week.
According to your logic, a week is in a month as long as its Thursday is in that month. If Thursday is in a month, then so are at least Monday, Tuesday, and Wednesday (if at the end) or Friday, Saturday, and Sunday (if at the beginning). So if you count the number of Thursdays in a month, you should get the number of weeks in that month.
Simply use LINQ to get all the days in a month, then take only days which are Thursday, then count those days
Public Function GetNumberOfWeeksInMonth(year As Integer, month As Integer) As Integer
Return Enumerable.Range(1, DateTime.DaysInMonth(year, month)).
Select(Function(d) New DateTime(year, month, d)).
Where(Function(d) d.DayOfWeek = DayOfWeek.Thursday).
Count()
End Function
' Concise version with Count with predicate
Public Function GetNumberOfWeeksInMonth(year As Integer, month As Integer) As Integer
Return Enumerable.Range(1, DateTime.DaysInMonth(year, month)).
Count(Function(d) (New DateTime(year, month, d)).DayOfWeek = DayOfWeek.Thursday)
End Function
Call it
For i = 1 To 12
Console.WriteLine($"{New DateTime(2020, i, 1):MMM}{vbTab}{GetNumberOfWeeksInMonth(2020, i)}")
Next
Jan 5
Feb 4
Mar 4
Apr 5
May 4
Jun 4
Jul 5
Aug 4
Sep 4
Oct 5
Nov 4
Dec 5
I assume this is something similar to the ISO 8601 scheme for year-weeks, where a week (a Mon-Sun period) falls into the year which contains it's Thursday.
Here a month contains a week if the Thursday of that week falls in the month.
Logically the number of such weeks in a month is the same as the number of Thursdays in that month.
You can derive this figure from the number of month-days in the month, and the week-day of the first month-day of the month.
A 28-day month always contains exactly 4 Thursdays. Months with more than 28 month-days may contain 5 Thursdays.
You can convert an ISO week-day number (Mon = 1, Sun = 7) to the following format like so: ((weekday + 2) Mod 7) - 2
Mon = 1, Tue = 2, Wed = 3, Thu = 4, Fri = -2, Sat = -1, Sun = 0
Then add this adjusted week-day figure to the number of month-days. If the result exceeds 32, then it is a month containing 5 weeks.
So a 31-day month starting on a Monday, produces a figure of 32 (31 + 1). It contains 4 weeks.
A 31-day month starting on a Tuesday, produces a figure of 33 (31 + 2). It contains 5 weeks.
A 31-day month starting on a Friday, produces a figure of 29 (31 + (-2)). It contains 4 weeks.
Hope this helps.

How can I calculate a fiscal week

I would like a column displaying the fiscal week. Our fiscal year begins in April.
So far I have the below, using datename(ww,DateAndTime) as Week
DateAndTime Week
2015-04-01 22:45 14
2015-06-14 13:22 25
2015-12-02 09:15 49
2016-01-01 07:35 1
I would like the output to show:
DateAndTime Week Fiscal Week
2015-04-01 22:45 14 1
2015-06-14 13:22 25 12
2015-12-02 09:15 49 36
2016-01-01 07:35 1 41
While I don't understand the logic behind the fiscal week (the difference between 1 and 41 is 40, but between 14 and 1 it's 39), maybe I'm missing something or you made a typo.
However, in general you'd do something like this (assuming the difference is 40 weeks):
SELECT week, (week+40)%52 AS fw FROM ...
If the fiscal year starts at a different week every each (say, 13th or 14th week depending on year), you can use the date and time functions, but they may vary between SQL versions. In MySQL you have YEAR(), MONTH(), WEEK(), etc.
For example:
SELECT week, (week+(52-WEEK(CONCAT_WS('-', YEAR(NOW()), '04-01'))))%52 FROM ...
But it might be overkill.
Note: It is possible to count the other way: if you subtract the diff from the week instead of adding, you will need to add 52 if the number is negative. You can do that by adding 52 and then doing modulo (%) 52.