2016-03-24 13 views
0

私はユーザーのテーブルを持っています。各ユーザーはSubscriptionStartDateとそのサブスクリプションが、私は時間をかけて月ごとにアクティブなサブスクリプションの数をカウントする必要が与えられた2つの日付の間にアクティブなサブスクライバをカウントする方法

を終了予定されていない場合、終了日はnullになる可能性が

SubscriptionEndDateを持って

私はこれを一度に1カ月にすることができますが、1年以上の毎月、一度にすべての結果を得ることができる単一のクエリが欲しいと思います。

declare @startDate datetime; 
declare @endDate datetime; 

set @startDate = '2-01-2016'; 
set @endDate = '2-29-2016' 

select COUNT(*) 
from Users 
where SubscriptionStartDate <= @startDate 
and (SubscriptionEndDate is null or SubscriptionEndDate>= @endDate) 

これを行うにはどうすればよいですか?

+0

ユーザーが1か月間アクティブだったかどうかを確認する方法はありますか? –

+0

サブスクリプションは、その月の最後の日にのみ終了すると仮定します – stephen776

答えて

1

タイムテーブルまたはCTEを使用して、APPLYを使用すると、このように試すことができます。

with months AS (
    select CONVERT(DATE,'2015-01-01') MonthStart, CONVERT(DATE,'2015-01-31') MonthEnd 
    union all 
    select dateadd(MONTH,1,MonthStart), dateadd(DAY,-1,dateadd(MONTH,2,MonthStart)) 
    from months 
    where 
     dateadd(MONTH,1,MonthStart) < GETDATE() 
) 
select 
    * 
from months m 
outer apply (
    select 
     COUNT(*) UserCount 
    from [Users] [U] 
    where 
     SubscriptionStartDate <= m.MonthEnd and 
     (ISNULL(SubscriptionEndDate,'3000-01-01')>= m.MonthStart) 
) Users 
OPTION (MAXRECURSION 0) 
0

確認したい範囲のすべての月の表またはCTEから始め、ユーザー表のサブスクリプション日付を使用してその表に結合します。

関連する問題