如何从sql server中的日期开始根据月份获取日期的周数

时间:2013-01-02 07:44:29

标签: sql sql-server-2008

我在表格中有一个日期列,我希望根据该日期的月份获取该特定日期的周数,而不管当天如何

例如:

01-dec-2012 to 07-dec-2012 should give week number as 1
08-dec-2012 to 14-dec-2012 should give week number as 2
15-dec-2012 to 21-dec-2012 should give week number as 3
22-dec-2012 to 28-dec-2012 should give week number as 4
29-dec-2012 to 31-dec-2012 should give week number as 5

本周数不依赖于一周的开始日,即可以是任何一天

如何编写select语句以在SQL Server 2008中获取此输出?

3 个答案:

答案 0 :(得分:6)

您可以使用DAY (Transact-SQL)

select ((day(DateColumn)-1) / 7) + 1
from YourTable

SQL Fiddle

MS SQL Server 2012架构设置

create table YourTable
(
  D datetime
)

insert into YourTable 
select getdate()+Number
from master..spt_values
where type = 'P' and
      Number between 1 and 15

查询1

select D,
       ((day(D)-1) / 7) + 1 as W
from YourTable

<强> Results

|                              D | W |
--------------------------------------
| January, 03 2013 07:48:54+0000 | 1 |
| January, 04 2013 07:48:54+0000 | 1 |
| January, 05 2013 07:48:54+0000 | 1 |
| January, 06 2013 07:48:54+0000 | 1 |
| January, 07 2013 07:48:54+0000 | 1 |
| January, 08 2013 07:48:54+0000 | 2 |
| January, 09 2013 07:48:54+0000 | 2 |
| January, 10 2013 07:48:54+0000 | 2 |
| January, 11 2013 07:48:54+0000 | 2 |
| January, 12 2013 07:48:54+0000 | 2 |
| January, 13 2013 07:48:54+0000 | 2 |
| January, 14 2013 07:48:54+0000 | 2 |
| January, 15 2013 07:48:54+0000 | 3 |
| January, 16 2013 07:48:54+0000 | 3 |
| January, 17 2013 07:48:54+0000 | 3 |

答案 1 :(得分:0)

Several options来做你想做的事。最有希望的似乎是使用DATEPART函数。但请注意,结果可能会因您的本地设置而异。

希望他们中的一个为你服务。

答案 2 :(得分:0)

试试这个

 declare @dates datetime
 select @dates='2012-12-22'
 SELECT datepart(dd,@dates), ceiling (cast(datepart(dd,@dates)as numeric(38,8))/7)