Getting week number of date in SQL

前端 未结 6 1382
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 08:26

Is there a way to get the week number of a date with SQL that is database independent?

For example to get the month of a date I use:

SELECT EXTRACT(MONTH         


        
相关标签:
6条回答
  • 2021-01-23 08:57

    You can try this.

    declare @date datetime select @date='2013-03-15 00:00:00' select 'Week No: '+ convert(varchar(10),datepart(wk,@date)) as weekno

    0 讨论(0)
  • 2021-01-23 08:59

    Try this one : SELECT DATENAME(yy,GETDATE())+RIGHT(DATENAME(wk,GETDATE()),2)

    To understand DATENAME, please follow this link : sqltutorials.blogspot.be/2007/05/sql-datename.html and for the right, suite101.com/article/sql-functions-leftrightsubstrlengthcharindex-a209089 . There are examples to better understand ;-) It will work on MS and other sql servers normally ;-)

    0 讨论(0)
  • 2021-01-23 09:03

    The only db independent solution I see is to get the number of days between today and Jan 1 of curr. year. Then divide it by 7 and round it up. There is 73 days from Jan 1 till today, which gives 10.43 as week number. The ISO week number is 11.

    Correction: the number of days between last day of the current week and Jan 1 of curr. year. In this case the ISO week is 10, and 68/7 = 10 (rounded).

    0 讨论(0)
  • 2021-01-23 09:03

    The best idea I found is

    SELECT ROUND(((DAY(NOW())-1)/7)+1)
    
    0 讨论(0)
  • 2021-01-23 09:06
    select (DATEPART(yyyy , CAST(GETDATE() AS datetime)) * 100 + 
            DATEPART(ww , CAST(GETDATE() AS datetime))) as week
    
    0 讨论(0)
  • 2021-01-23 09:10

    There doesn't appear to be a single standard SQL function to extract the week number from a date - see here for a comparison of how different SQL dialects can extract different dateparts from date fields.

    0 讨论(0)
提交回复
热议问题