[英]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. 在上述CTE中,所需的输出应基于我的开始和结束日期给出12月,1月和2月的输出。
Change the where query only:- 更改仅where查询:
DateAdd(Month,0,dat)< @end_date DateAdd(Month,0,dat)<@结束日期
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.