您可以按如下方式生成月份列表:
SELECT add_months (trunc (to_date('01/01/2012','MM/DD/YYYY'), 'MM'), 1*LEVEL -1) FirstDay
FROM Dual
CONNECT BY LEVEL <= MONTHS_BETWEEN(to_date('12/31/2012','MM/DD/YYYY'), to_date('01/01/2012','MM/DD/YYYY')) + 1
ORDER BY FirstDay
这将为您提供以下输出:
FIRSTDAY
--------
January, 01 2012 00:00:00+0000
February, 01 2012 00:00:00+0000
March, 01 2012 00:00:00+0000
April, 01 2012 00:00:00+0000
May, 01 2012 00:00:00+0000
June, 01 2012 00:00:00+0000
July, 01 2012 00:00:00+0000
August, 01 2012 00:00:00+0000
September, 01 2012 00:00:00+0000
October, 01 2012 00:00:00+0000
November, 01 2012 00:00:00+0000
December, 01 2012 00:00:00+0000
然后,您可以将该查询包含为内联视图,如下所示:
SELECT months.FirstDay,
(SELECT count(subscribers)
FROM subscriberlist sub
WHERE months.FirstDay BETWEEN sub.firstDayOfSubscription AND sub.lastDayOfSubscription
) AS activeSubscribers
FROM (SELECT add_months(trunc (to_date('01/01/2012','MM/DD/YYYY'), 'MM'), 1*LEVEL -1) FirstDay
FROM Dual
CONNECT BY LEVEL <= MONTHS_BETWEEN(to_date('12/31/2012','MM/DD/YYYY'), to_date('01/01/2012','MM/DD/YYYY')) + 1
ORDER BY FirstDay) Months
我可能会将它包装在一个接受 @startDate 和 @endDate 参数的存储过程中,以定义您感兴趣的日期范围,但我遵循您的语法,日期范围是用字符串定义的。
我正在使用这个SqlFiddle玩这个