Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract week number in sql

Tags:

I have a transdate column of varchar2 type which has the following entrees

01/02/2012 01/03/2012 

etc.

I converted it in to date format in another column using to_date function. This is the format i got.

01-JAN-2012 03-APR-2012 

When I'm trying to extract the weekno, i'm getting all null values.

select to_char(to_date(TRANSDATE), 'w') as weekno from tablename.

null null 

How to get weekno from date in the above format?

like image 775
user2133404 Avatar asked May 13 '13 19:05

user2133404


People also ask

How do I get weekly week data in SQL?

WEEK() function in MySQL is used to find week number for a given date. If the date is NULL, the WEEK() function will return NULL. Otherwise, it returns the value of week which ranges between 0 to 53. The date or datetime from which we want to extract the week.

How do I get last 7 days record in SQL?

Here's the SQL query to get records from last 7 days in MySQL. In the above query we select those records where order_date falls after a past interval of 7 days. We use system function now() to get the latest datetime value, and INTERVAL clause to calculate a date 7 days in the past.


2 Answers

After converting your varchar2 date to a true date datatype, then convert back to varchar2 with the desired mask:

to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW') 

If you want the week number in a number datatype, you can wrap the statement in to_number():

to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')) 

However, you have several week number options to consider:

WW  Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year. W   Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh. IW  Week of year (1-52 or 1-53) based on the ISO standard. 
like image 97
Wolf Avatar answered Oct 22 '22 12:10

Wolf


Try to replace 'w' for 'iw'. For example:

SELECT to_char(to_date(TRANSDATE, 'dd-mm-yyyy'), 'iw') as weeknumber from YOUR_TABLE; 
like image 30
Vinicius Lima Avatar answered Oct 22 '22 11:10

Vinicius Lima