使用spt_values和cte生成日曆,這裏是一個計數成員的示例。
declare @members table (member int, start_date date, end_date date)
insert @members select 1, '2015-12-15', '2017-01-15'
insert @members select 2, '2016-01-15', '2016-12-15'
insert @members select 3, '2016-03-01', '2016-10-31'
declare @cal_from datetime = '2016-01-01';
declare @cal_to datetime = '2016-12-31';
with calendar_cte as (
select top (datediff(month, @cal_from, @cal_to) + 1)
[Month] = month(dateadd(month, number, @cal_from))
, [Year] = year(dateadd(month, number, @cal_from))
, [Start] = dateadd(month, number, @cal_from)
, [End] = dateadd(day, -1, dateadd(month, number + 1, @cal_from))
from [master].dbo.spt_values
where [type] = N'P'
order by number
)
select [Month]
, [Year]
, [Count] = (select count(*)
from @members
where start_date <= [Start]
and end_date >= [End])
from calendar_cte
爲什麼你給了就不會在Mar.2015成員的例子嗎? – LONG
例如,如果我們計算2014年12月的會員資格,那麼我將按[會員從日期] <='2014-12-01'和[會員至日期]> ='2014-12-31'進行過濾。希望澄清。謝謝! – Baldy