I am using DB2 SQL, where I have a reference date - and would like to count distinct individuals that for each monthdiff either side (increasing up to the START_DT/END_DT) of the REF_DT - return a row, with the month counter.
My base data looks like:
ID REF_DT START_DT END_DT
-- ------ -------- ------
1 2000-01-01 1998-01-01 2002-01-01
2 2001-06-01 2001-06-01 2003-06-01
3 2003-01-01 1998-01-01 2005-06-01
4 2002-05-01 2003-01-01 2005-01-01
so taking the first row, I return a row for each month around the REF_DT
that exists between START_DT
and END_DT
and return the value of the monthdiff. The first row in my base table would generate:
ID REF_DT START_DT END_DT MONTHDIFF
-- ------ -------- ------ ---------
1 2000-01-01 1998-01-01 2002-01-01 -24
1 2000-01-01 1998-01-01 2002-01-01 -23
.
.
.
1 2000-01-01 1998-01-01 2002-01-01 24
i.e. would produce 48 rows as the START_DT
and END_DT
are 24 months either side of the REF_DT
I could to this query by query i.e.
select distinct id, ref_dt,start_dt,end_dt,
case when ref_dt - 1 month between start_dt and end_dt then -1 end as monthdiff
however I would have to manually create 1 row per query. I wish to embed this logic in something a bit more clever than that.
Thanks.
SOLVED
see Juan's suggestion for the answer. The idea to create a table for just the month reference worked. I created this table by looking at the following stack thread generate_series() equivalent in DB2