使用sql server中的公用表表达式计算月份号,月份名称,月份的第一天(日期)和月份的最后一天(日期)?

时间:2014-09-16 04:48:25

标签: sql sql-server-2008 sql-server-2005

declare @start_date as datetime = '12/31/2014'
declare @end_date as datetime = '02/15/2015'

;with cte as (
   select 
       datename(month,@start_date) as [mnth_nm],
       month(@start_date) as [mnth_no],
       @start_date as dat,
       DATEADD(DAY, -1 * DAY(@start_date) + 1, @start_date) as [first_day],
       DATEADD(dd, -DAY(DATEADD(mm, 1, @start_date)), DATEADD(mm, 1, @start_date)) as [last_day]
   union all
   select 
      datename(month, DateAdd(Month, 1, dat)),
      month(dat) + 1 as [mnth_no],
      DateAdd(Month, 1, dat), 
      DATEADD(MONTH, 1, [first_day]), 
      DATEADD(dd, -DAY(DATEADD(mm, 1, dat)), 
      DATEADD(mm, 1, dat)) + 1 
   from 
      cte
   where 
      DateAdd(Month,1,dat) < @end_date
)
select 
    [mnth_nm], [mnth_no], @start_date, [first_day], [last_day] 
from 
    CTE

在上述CTE中,所需的输出应根据我的开始和结束日期给出12月,1月和2月的月份输出。

2 个答案:

答案 0 :(得分:0)

仅更改where查询: -

使用DateAdd(月,0,DAT)&LT; @end_date

答案 1 :(得分:0)

<b>Got the solution ... </b>
<p>
declare @start_date as datetime = '12/31/2014'
declare @end_date as datetime = '03/15/2015'

;with cte as (
   select 
       datename(month,@start_date) as [mnth_nm],
       month(@start_date) as [mnth_no],
       @start_date as dat,
       DATEADD(DAY, -1 * DAY(@start_date) + 1, @start_date) as [first_day],
       DATEADD(dd, -DAY(DATEADD(mm, 1, @start_date)), DATEADD(mm, 1, @start_date)) as [last_day]
   union All
   select 
      datename(month, DateAdd(Month, 1, dat)),
      month(DateAdd(m,1,dat)) as [mnth_no],
      DateAdd(Month, 1, dat), 
      DATEADD(MONTH, 1, [first_day]), 
DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, DATEADD(MONTH, 1, [first_day])) + 1, 0)) 
   from 
      cte
   where 
    DateAdd(Month,0,dat)<  @end_date
)
select 
    [mnth_nm], [mnth_no], @start_date, [first_day], [last_day] 
from 
    CTE</p>