我需要在 sql 下执行 12 个月(Apr12,May12,Jun12...Apr13) 但不想多次执行或重写我的 sql。试图确定是否有办法将其作为递归 cte 的一部分。需要确保月份日期正确(每隔一个月是 30/31 天,2 月有 28 天)。
这是我的sql
Select
--Month of Apr 2012
(Select 1.0 * 100 *
(
Select COUNT(*)
from B b
left outer join F f on f.id = b.id
Where f.date1 < '05/01/2012' and
(f.date2 between '04/01/2012' and '04/30/2012' or f.date2 is Null)
)
/
(Select COUNT(*)
from f
Where date1 < '05/01/2012' and
(date2 between '04/01/2013' and '04/30/2013' or date2 is Null)) as 'Apr 2012',
--Month of May 2012
(Select 1.0 * 100 *
(
Select COUNT(*)
from B b
left outer join F f on f.id = b.id
Where f.date1 < '06/01/2012' and
(f.date2 between '05/01/2012' and '05/31/2012' or f.date2 is Null)
)
/
(Select COUNT(*)
from f
Where date1 < '06/01/2012' and
(date2 between '05/01/2013' and '05/31/2013' or date2 is Null)) as 'May 2012'