Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem when extracting year and week number from string in PSQL

Let's say that I have a range of SQL tables that are named name_YYYY_WW where YYYY = year and WW = week number. If I call upon a function that guides a user defined date to the right table.

If the date entered is "20110101":

SELECT EXTRACT (WEEK FROM DATE '20110101') returns 52 and

SELECT EXTRACT (YEAR FROM DATE '20110101') returns 2011.

While is nothing wrong with these results I want "20110101" to either point to table name_2010_52 or name_2011_01, not name_2011_52 as it does now when I concanate the results to form the query for the table.

Any elegant solutions to this problem?

like image 558
Joshua Avatar asked May 18 '11 12:05

Joshua


People also ask

How do I get the current week number in PostgreSQL?

Use the DATE_PART() function to retrieve the week number from a date in a PostgreSQL database. This function takes two arguments. The first argument is the date part to retrieve; we use 'week', which returns the week number (e.g. “1” for the first week in January, the first week of the year).

How do I extract the day of the week in PostgreSQL?

To extract the day name from the date, you can use the to_char() function. The first parameter is the date and the second is the desired output format. To extract the full day name, the format should be 'Day' : SELECT to_char( date '2022-01-01' , 'Day' );

Which function can be used to convert strings to date in PostgreSQL?

The TO_DATE function in PostgreSQL is used to converting strings into dates. Its syntax is TO_DATE(text, text) and the return type is date. The TO_TIMESTAMP function converts string data into timestamps with timezone. Its syntax is to_timestamp(text, text) .

How do I select data between two dates in PostgreSQL?

Use the PostgreSQL AGE() function to retrieve the interval between two timestamps or dates. This function takes two arguments: the first is the end date and the second is the start date.


1 Answers

The function to_char() will allow you to format a date or timestamp to output correct the iso week and iso year.

SELECT to_char('2011-01-01'::date, 'IYYY_IW') as iso_year_week;

will produce:

 iso_year_week 
---------------
 2010_52
(1 row)
like image 117
Haes Avatar answered Oct 27 '22 01:10

Haes