1

我在表格中有一个日期列,我想根据该日期的月份获取该特定日期的周数,而不考虑日期

例如:

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 中获取此输出?

4

3 回答 3

6

您可以使用DAY (Transact-SQL)

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

SQL小提琴

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

结果

|                              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 |
于 2013-01-02T07:48:40.773 回答
0

这里有几个选项可以做你想做的事。其中最有希望的似乎是使用该DATEPART功能。但请注意,结果可能会因您的本地设置而异。

希望其中一个适合你。

于 2013-01-02T07:47:05.420 回答
0

试试这个

 declare @dates datetime
 select @dates='2012-12-22'
 SELECT datepart(dd,@dates), ceiling (cast(datepart(dd,@dates)as numeric(38,8))/7)
于 2013-01-02T07:49:46.470 回答