Extract matching year for week number in postgresql - postgresql

In postgresql extract(week from '2014-12-30'::timestamp) gives week number 1 of 2015. How do I extract the associated year that corresponds to the week number? Using extract(year ... gives 2014

Since week is the ISO-defined week, you want the isoyear:
#= select extract(isoyear from '2014-12-30'::timestamp);
date_part
-----------
2015
(1 row)
From the docs:
By definition, ISO weeks start on Mondays and the first week of a year
contains January 4 of that year. In other words, the first Thursday of
a year is in week 1 of that year.
In the ISO week-numbering system, it is possible for early-January
dates to be part of the 52nd or 53rd week of the previous year, and
for late-December dates to be part of the first week of the next year.
For example, 2005-01-01 is part of the 53rd week of year 2004, and
2006-01-01 is part of the 52nd week of year 2005, while 2012-12-31 is
part of the first week of 2013. It's recommended to use the isoyear
field together with week to get consistent results.

According to the postgresql documentation for extract week:
The number of the week of the year that the day is in. By definition
(ISO 8601), the first week of a year contains January 4 of that year.
(The ISO-8601 week starts on Monday.) In other words, the first
Thursday of a year is in week 1 of that year. (for timestamp values
only)
Based on this, you might have to do a little logic:
case when extract(week from '2014-12-30'::timestamp) = 1
and extract(month from '2014-12-30'::timestamp) = 12
then extract(year from '2014-12-30'::timestamp)+1
else extract(year from '2014-12-30'::timestamp)
end

Related

Group date by week number in the form YYYY-MM-WW

Currently have rows aggregated by week number.
SELECT to_char(date, 'IYYY-MM-IW') AS week, from TABLE GROUP BY week
The results will show the form "2021-07-29". Is it possible to change the week number such that it is the number week of the month (instead of year).
For example, instead of "2021-07-29", we convert to "2021-07-04" since the 29th week of the year is actually the 4th week of the month.
Quote from the manual
W week of month (1–5) (the first week starts on the first day of the month)
So you can use:
to_char(date, 'YYYY-MM-W')
For e.g 2021-10-18 this yields 2021-10-3 (third week in October)

Week Number restarting at 1 every month as per ISO format in Tableau

I am trying to get week numbers ( resetting at 1 for each month) as per ISO format for each month in 2019.For example I am interested in getting
All dates in July 2019: week 1 to 4,
All dates in Aug 2019 : week 1 to 4 and so on.
I first created the calculated field (Week_Number_ISO) to get the overall week number in year 2019.I used the following formula;
DATEPART('iso-week',[ Date]) which works as intended.
To get the monthly week number I used the following formula
INT((DATEPART('day',[Created Date])-DATEPART('iso-weekday',[Created Date])+7)/7)+1.
(Idea was to calculate the date of the first day of each week & then divide by 7 and take the integer part)
As per the ISO format, shouldn't July 29 to 31st be a part of week 4 for July?But the formula is showing it as week 5 for July 2019.I feel I am missing something in the formula or am missing something about ISO week number resetting at 1 for each month.
Can someone help me?
Here is an example of the dates in July 2019 and the associated week numbers.
Why would July 28th-July 31st 2019 be considered week 4?

TSQL ISO Month Week Number for ISO Year Week Number

Using TSQL I need to get the ISO Week Number in a Month for a give ISO Year Week Number.
For example: The following code will give me Week #1 for 12/31/2001, which is correct. It is the first Monday in 2002 and the first day of the ISO Year 2002.
select DATEPART(ISO_WEEK, '12-31-2001'); --Week 1 January 2002
My question is how do I...
(1) Take the ISO Week Number Example: ISO Year Week Number: 14 for April 4, 2016 (April Week #1).
(2) Now Take ISO Year Week Number 14 and return April Month Week Number = 1 for the example above.
There seems to be nothing in SQL Server to get the ISO Month Week# from the ISO Year Week Number. I have a function I wrote but it is has some hacks to get it to work, but not 100%.
I think you want something like this... but am not sure why you need the ISO_WEEK. Just replace getdate() with your column.
select datepart(wk, getdate()) - datepart(wk,dateadd(m, DATEDIFF(M, 0, getdate()), 0)) + 1
After attempting to handle getting ISO Month Week Number in functions I decided an easier solution was to create an ISO_Calendar table in SQL Sever.
We know in TSQL you can get the ISO Year Week Number and some a bit of work the ISO Year Number. The ISO Month Week Number is another story.
I build the table shown below with data from 2000 to 2040 by populating all the columns other than the ISO Month number. Then on a second pass I looped through the table and set the ISO Month number based on the Month# in the Monday Date.
Now if I want to get the ISO Month number for a date I check #Date between Monday and Sunday. In my case I am only concerned with dates between Monday and Friday since this is for a stock analysis site.
select #ISOMonthWeekNo = c.ISOMonthWeekNo
from ISO_Calendar c
where #TransDate between c.Monday and c.Sunday;
The advantage is the table is a one time build and easier to verify the accuracy of the data.

DB2 separate number of weeks per quarter from timestamp

I'm trying to separate weeks from timestamp per quarter so it should be between 1-13 week per quarter so I used function week() but it takes between 1-52 week as whole year so I made it to be divided by function of quarter like below
select Week (EVENTTIMESTAMP) / QUARTER (EVENTTIMESTAMP) from KAP
The thing here that results aren't accurate; for example it shows:
time stamp 2014-07-06 12:13:03.018
week number 9
which isn't correct because July is first month in Q3 and it's in the 6 days so it should be 1 week from Q3 not 9.
Any suggestion where it go wrong?
You want something like WEEK modulo 13 to get week number within a quarter. You will have to tinker with 'modulo 13 yields 0..12' by adding or subtracting one at appropriate points.
Some minimal Google searching using 'ibm db2 sql modulo' yields DB2 MOD function:
The MOD function divides the first argument by the second argument and returns the remainder.
Hence MOD(WEEK(...), 13), except you probably need MOD(WEEK(...)-1, 13) + 1, as intimated already.
You may need to watch for what the WEEK() function does at year ends:
The WEEK function returns an integer in the range of 1 to 54 that represents the week of the year. The week starts with Sunday, and January 1 is always in the first week.
I'm curious about how they can come up with week 54. I suppose it requires 1st January to be a Saturday (so 2nd January is the start of week 2) of a leap year, as in 2000 and 2028. Note that week 53 and (occasionally) week 54 will show up as weeks 1 and 2 of Q5 unless you do something. Also, Saturday 2000-03-25 would be the end of Q1 and Sunday 2000-03-26 would be the start of Q2 under the regime imposed by the WEEK() function and a simple MOD(WEEK(...), 13) calculation. You're likely to have to tune this to meet your real requirements.
There's also the WEEK_ISO() function:
The WEEK_ISO function returns an integer in the range of 1 to 53 that represents the week of the year. The week starts with Monday and includes seven days. Week 1 is the first week of the year that contains a Thursday, which is equivalent to the first week that contains January 4.
Note that under the ISO scheme, the 3rd of January can be in week 52 or 53 of the previous year, and the 29th of December can be in week 1 of the next year. Curiously, there doesn't seem to be a YEAR_ISO() function to resolve such ambiguities.
In a data warehouse, the proper solution to this is to create a time dimension that contains static mappings for days/weeks/months/quarters/years. This provides the ability to define these based on your business' fiscal calendar (if it is not following on the calendar year).
See: http://www.kimballgroup.com/1997/07/10/its-time-for-time/ for more information.

SQL DateDiff Weeks - Need and alternative

The MS SQL DateDiff function counts the number of boundaries crossed when calculating the difference between two dates.
Unfortunately for me, that's not what I'm after. For instance, 1 June 2012 -> 30 June 2012 crosses 4 boundaries, but covers 5 weeks.
Is there an alternative query that I can run which will give me the number of weeks that a month intersects?
UPDATE
To try and clarify exactly what I'm after:
For any given month I need the number of weeks that intersect with that month.
Also, for the suggestion of just taking the datediff and adding one, that won't work. For instance February 2010 only intersects with 4 weeks. And the DateDiff calls returns 4, meaning that simply adding 1 would leave me the wrong number of weeks.
Beware: Proper Week calculation is generally trickier than you think!
If you use Datepart(week, aDate) you make a lot of assumptions about the concept 'week'.
Does the week start on Sunday or Monday? How do you deal with the transition between week 1 and week 5x. The actual number of weeks in a year is different depending on which week calculation rule you use (first4dayweek, weekOfJan1 etc.)
if you simply want to deal with differences you could use
DATEDIFF('s', firstDateTime, secondDateTime) > (7 * 86400 * numberOfWeeks)
if the first dateTime is at 2011-01-01 15:43:22 then the difference is 5 weeks after 2011-02-05 15:43:22
EDIT: Actually, according to this post: Wrong week number using DATEPART in SQL Server
You can now use Datepart(isoww, aDate) to get ISO 8601 week number. I knew that week was broken but not that there was now a fix. Cool!
THIS WORKS if you are using monday as the first day of the week
set language = british
select datepart(ww, #endofMonthDate) -
datepart(ww, #startofMonthDate) + 1
Datepart is language sensistive. By setting language to british you make monday the first day of the week.
This returns the correct values for feburary 2010 and june 2012! (because of monday as opposed to sunday is the first day of the week).
It also seems to return correct number of weeks for january and december (regardless of year). The isoww parameter uses monday as the first day of the week, but it causes january to sometimes start in week 52/53 and december to sometimes end in week 1 (which would make your select statement more complex)
SET DATEFIRST is important when counting weeks. To check what you have you can use select ##datefirst. ##datefirst=7 means that first day of week is sunday.
set datefirst 7
declare #FromDate datetime = '20100201'
declare #ToDate datetime = '20100228'
select datepart(week, #ToDate) - datepart(week, #FromDate) + 1
Result is 5 because Sunday 28/2 - 2010 is the first day of the fifth week.
If you want to base your week calculations on first day of week is Monday you need to do this instead.
set datefirst 1
declare #FromDate datetime = '20100201'
declare #ToDate datetime = '20100228'
select datepart(week, #ToDate) - datepart(week, #FromDate) + 1
Result is 4.