如何查找特定于月份的第一个和最后一个星期?

时间:2010-07-16 05:46:34

标签: sql sql-server

如何找到getdate()传递后一个月特定的第一个和最后一个星期?

例如:

Case 1
Today is '16 July 2010'
I want
Week_Start_Date as '11 July 2010'
and 
Week_End_Date as '17 July 2010'

Case 2
Today is '2 July 2010'
I want
Week_Start_Date as '1 July 2010'
and 
Week_End_Date as '3 July 2010'

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:2)

试试这个,您可能需要修改添加和减去GetDate()的一天以获得您正在寻找的范围,但实质上这应该适合您想要的。

select convert(date, dateadd(d, -datepart(dw, getdate()), getdate())) as FirstDay
select convert(date, dateadd(d, 7-datepart(dw, getdate()), getdate())) as LastDay

答案 1 :(得分:2)

使用Calendar table

SQL是一种声明性语言,在计算方面没有那么好,特别是在时间上,所以寻找声明性的,数据驱动的解决方案。

创建一个辅助日历表,其中包含所有适用日期,例如未来20年和过去几年。添加week_start_dateweek_end_date的列,然后根据规范中的算法为每天填充正确的值。这是你的SQL DDL(虽然我建议你使用电子表格创建数据然后导入它,然后应用约束,索引等)。

对于SQL DML,只需在Calendar表中查找CURRENT_TIMESTAMP(标准等效getdate),即查询而不是计算。

答案 2 :(得分:0)

我写了一个函数来帮助我满足我的要求。我发布代码以防任何人需要它:

Declare @FirstDayOfMonth as Datetime
Declare @LastDayOfMonth as Datetime
Declare @CurrentDate as Datetime
Declare @MinDate as Datetime
Declare @MaxDate as Datetime
Declare @MaxWeekNo as int
Declare @PresentWeekNo as int

Set @CurrentDate = '31 October 2010'

set @FirstDayOfMonth = DATEADD(month,(DATEDIFF(month,0,@CurrentDate)), 0)
set @LastDayOfMonth = dateadd(mm,1,@CurrentDate - day(@CurrentDate)+1)-1
set @MaxWeekNo = dbo.FINDINWEEK(@LastDayOfMonth)
set @PresentWeekNo = dbo.FINDINWEEK(@CurrentDate)

set @MinDate = 
Case when @PresentWeekNo = 1 then
    CAST(MONTH(@CurrentDate) AS VARCHAR(2))+'/'+'1'+'/'+ CAST(YEAR(@CurrentDate) AS VARCHAR(4))
Else
    DATEADD(dd,-(DATEPART(dw, @CurrentDate) - 1),@CurrentDate)
End

set @MaxDate = 
Case when @MaxWeekNo = 4 then
    Case when @PresentWeekNo = 4 then
        CAST(MONTH(@CurrentDate) AS VARCHAR(2))+'/'+CAST(day(@LastDayOfMonth) as VARCHAR(2))+'/'+ CAST(YEAR(@CurrentDate) AS VARCHAR(4))
    Else
        DATEADD(dd,-(DATEPART(dw, @CurrentDate) - 7),@CurrentDate)
    End
when @MaxWeekNo = 5 then
    Case when @PresentWeekNo = 5 then
        CAST(MONTH(@CurrentDate) AS VARCHAR(2))+'/'+CAST(day(@LastDayOfMonth) as VARCHAR(2))+'/'+ CAST(YEAR(@CurrentDate) AS VARCHAR(4))
    Else
        DATEADD(dd,-(DATEPART(dw, @CurrentDate) - 7),@CurrentDate)
    End
when @MaxWeekNo = 6 then
    Case when @PresentWeekNo = 6 then
        CAST(MONTH(@CurrentDate) AS VARCHAR(2))+'/'+CAST(day(@LastDayOfMonth) as VARCHAR(2))+'/'+ CAST(YEAR(@CurrentDate) AS VARCHAR(4))
    Else
        DATEADD(dd,-(DATEPART(dw, @CurrentDate) - 7),@CurrentDate)
    End
End 

Print @MinDate
Print @MaxDate