简体   繁体   中英

Calculate month number,month name, first day of month(date) and last day of month(date) using common table expression in sql server?

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

In above CTE the required output should give december, january and february month output based on my start and end date.

Change the where query only:-

DateAdd(Month,0,dat)< @end_date

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM