This is a successor question to this question which explains the objective of this query and provides a sample of the source data.
With help, I have this recursive query running which is more efficient than my non-recursive query, repeated 36 times and unioned together.
The purpose of this query is to know which department an employee was in at the end of each month. The problem with this code is that for employees who changed departments, it is returning only the month end department value for months subsequent to the most recent department change, and no prior records. For employees who changed departments, the output should contain this data:
Month - Department Code
0 - 100
1 - 100
2 - 200
3 - 200
And it is currently returning:
Month - Department Code
0 - 100
1 - 100
Here is the query:
WITH Q AS (
select
row_number() over(order by null) as q_level,
last_day(dateadd(month, -q_level, CURRENT_DATE), month) as last_day_month
from table(generator(ROWCOUNT=>36))
), Q1 AS (
select
q.q_level
,q.last_day_month
,v_dept_history_adj.associate_id
,v_dept_history_adj.home_department_code
,v_dept_history_adj.position_effective_date
,max(position_effective_date) OVER(PARTITION BY v_dept_history_adj.associate_id) AS most_recent_record
from datawarehouse.srctable
,Q
where v_dept_history_adj.position_effective_date <= q.last_day_month
)
select
associate_id
,position_effective_date
,home_department_code
,most_recent_record
,last_day_month AS month
FROM Q1
where position_effective_date = most_recent_record
order by month desc, position_effective_date desc