How to extract week number in sql

心已入冬 提交于 2019-11-26 11:18:41

问题


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?


回答1:


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.



回答2:


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

SELECT to_char(to_date(TRANSDATE, 'dd-mm-yyyy'), 'iw') as weeknumber from YOUR_TABLE;



回答3:


Select last_name, round (sysdate-hire_date)/7,0) as tuner 
  from employees
  Where department_id = 90 
  order by last_name;



回答4:


Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')


来源:https://stackoverflow.com/questions/16530044/how-to-extract-week-number-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!