So I have this query that gives me a count of accounts that had a certain kind of transaction at least once in every month in the given time frame. In this case I'm checking for transactions over a 3 month period. See query below:
select
Yr
, count(distinct acct_nbr) as AcctCt
from (
select
Yr
, acct_nbr
, count(distinct Mth) as Mths
from (
select
extract(year from tran_dt) as Yr
, acct_nbr
, extract(month from tran_dt) as Mth
, tran_id
from br.bdft
where prod_type = 44
and (tran_dt between '2017-10-01' and '2017-12-31'
or tran_dt between '2016-10-01' and '2016-12-31'
or tran_dt between '2015-10-01' and '2015-12-31'
or tran_dt between '2014-10-01' and '2014-12-31'
or tran_dt between '2013-10-01' and '2013-12-31')
and tran_cd = 'DD'
) dt
group by 1,2
) dt2
where Mths = 3
group by 1
The results I'm getting are as follows:
Yr: AcctCt:
2017 258527
2016 231304
2015 188550
2014 210339
2013 170781
I'm currently grouping the results by YEAR, by extracting the YEAR from the transaction date. This works fine when then date ranges don't cross years (e.g. what I'm using in my query above). But once I cross years, e.g. 2017-11-01 to 2018-01-31, this approach no longer works.
Is there a better way to group results where it always works irrespective of the date range I'm using?