Getting week number of date in SQL

2019-03-01 16:21发布

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 FROM :DATE)

But the EXTRACT function doesn't know about weeks in SQL92.

Please pay attention to the fact that I want a solution that is database independent! Do not misinterpret this as a question regarding MS SQL Server.

6条回答
劳资没心,怎么记你
2楼-- · 2019-03-01 16:33

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

查看更多
Deceive 欺骗
3楼-- · 2019-03-01 16:39

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.

查看更多
虎瘦雄心在
4楼-- · 2019-03-01 16:39

The best idea I found is

SELECT ROUND(((DAY(NOW())-1)/7)+1)
查看更多
ゆ 、 Hurt°
5楼-- · 2019-03-01 16:41
select (DATEPART(yyyy , CAST(GETDATE() AS datetime)) * 100 + 
        DATEPART(ww , CAST(GETDATE() AS datetime))) as week
查看更多
时光不老,我们不散
6楼-- · 2019-03-01 16:43

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).

查看更多
劳资没心,怎么记你
7楼-- · 2019-03-01 16:56

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 ;-)

查看更多
登录 后发表回答