@@ -230,6 +230,15 @@ def computed_keys() -> list[str]:
230230 def _current_fetch_query (start_time : datetime ) -> str : # noqa: ARG004
231231 hstry = ALIAS_HSTRY
232232 xref = ALIAS_XREF
233+ # There can be multiple xref records for the same bene_sk/bene_ref_sk combo
234+ # so we need to find the most recent one based on src_rec_updt_ts.
235+
236+ # Unlike idr_updt_ts, src_rec_updt_ts will be set to the created timestamp
237+ # if no update has been applied. Therefore, we can just check the updated timestamp
238+ # without caring about the created timestamp.
239+
240+ # There can also be duplicate values with the same idr_insrt_ts, so we have to rely on
241+ # src_rec_insrt_ts/src_rec_updt_ts for this.
233242 return f"""
234243 WITH ordered_xref AS (
235244 SELECT bene_sk, bene_xref_sk, ROW_NUMBER() OVER (
@@ -247,12 +256,14 @@ def _current_fetch_query(start_time: datetime) -> str: # noqa: ARG004
247256 bx.idr_insrt_ts,
248257 bx.idr_updt_ts
249258 FROM ordered_xref ox
250- JOIN cms_vdm_view_mdcr_prd.v2_mdcr_bene_xref bx
259+ JOIN cms_vdm_view_mdcr_prd.v2_mdcr_bene_xref bx
251260 ON bx.bene_sk = ox.bene_sk AND bx.bene_xref_sk = ox.bene_xref_sk
252261 WHERE ox.row_order = 1
253262 )
254263 SELECT {{COLUMNS}}
255264 FROM cms_vdm_view_mdcr_prd.v2_mdcr_bene_hstry { hstry }
265+ -- NOTE: the join condition is intentionally inverted here
266+ -- In the xref table, the bene_sk and bene_xref_sk fields are mirrored
256267 LEFT JOIN current_xref { xref }
257268 ON { xref } .bene_sk = { hstry } .bene_xref_sk
258269 AND { xref } .bene_xref_sk = { hstry } .bene_sk
0 commit comments