2014-10-20 50 views
0

我有这个逻辑,但我不知道该怎么做才能拿出结果。我想要达到下面的结果,这个想法是(2014年10月),通常是5周。如果有第五周并且天数大于3,那么在下个月考虑整周,否则将其添加到第四周。如何显示每周4个星期的条件在sql

Input: 
    date range 

    from: 10-01-2014 
    to: 11-30-2014 

    Sample Output: 

    Date  Customer  week#   Dates covered 
    10-01-2014  Cust01   1   Oct 01 - Oct 11, 2014 
    10-08-2014  Cust02   1   Oct 01 - Oct 11, 2014 
    10-17-2014  Cust02   2   Oct 12 - Oct 18, 2014 
    10-25-2014  Cust03   3   Oct 19 - Oct 25, 2014 
    10-31-2014  Cust01   4   Oct 26 - Oct 31, 2014 
    11-01-2014  Cust01   1   Nov 01 - Nov 08, 2014 
    11-28-2014  Cust02   4   Nov 23 - Nov 30, 2014 
    11-30-2014  Cust05   4   Nov 23 - Nov 30, 2014 

Thanks 
+0

你的逻辑有问题时,有6个星期,一个月,如2014年Noverver你能不能打一个比方输出由2014年11月? – 2014-10-21 01:30:06

+0

在11月份的情况下,nov 1将在第1周增加到nov2-8,并且nov 30在第4周将成为nov 23-29的一部分。 – Tinapay 2014-10-21 03:40:40

+0

因此,在28天的2月从周三开始,您只需要3周? – 2014-10-21 05:15:23

回答

0

使用datepart(ww,[date])得到周数在一年内,然后通过一个月的开始日期比较周数。

下面是具体的方法来计算一个日期:

declare @dt date, @month_begin date, @month_end date, @week_of_month int 
set @dt='20141031' 
set @month_begin = convert(date,(convert(char(6),@dt,112)+'01')) 
set @month_end = dateadd(day, -1, dateadd(month,1,@month_begin)) 
set @week_of_month = datepart(ww,@dt) - datepart(ww,convert(date,(convert(char(6),@dt,112)+'01'))) + 1 
select 
    case when @week_of_month > 4 and datepart(dw,@month_end)>3 
     then 1 
     else @week_of_month 
    end as week, 
    case when @week_of_month > 4 and datepart(dw,@month_end)>3 
     then datepart(month,dateadd(month,1,@dt)) 
     else datepart(month,@dt) 
    end as month 
相关问题