Skip to content

Commit a168ae3

Browse files
committed
fix: Update SQL script for closed_dimension_id_date to use subquery for next closed action
- Refactored the SQL update logic to replace LATERAL with a subquery using DISTINCT ON, ensuring accurate pairing of opened facts with their immediate closed actions. - Improved clarity and performance of the update process by optimizing the selection of next closed dates, hours, and users for opened facts.
1 parent 4538e35 commit a168ae3

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

sql/dwh/Staging_35b_updateClosedDimensionIdDate.sql

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,29 @@ CREATE INDEX IF NOT EXISTS facts_id_note_action_at_idx ON dwh.facts (id_note, ac
1919
-- Update closed_dimension_id_date for opened facts where note has been closed
2020
-- Strategy: For each opened fact, find the NEXT closed action that occurs AFTER it
2121
-- This correctly pairs each opened fact with its immediate close, not the most recent close
22+
-- Note: Cannot use LATERAL in UPDATE FROM, so we use a subquery with DISTINCT ON to find the next close
2223
UPDATE dwh.facts f_opened
2324
SET
2425
closed_dimension_id_date = closed_info.next_closed_date,
2526
closed_dimension_id_hour_of_week = closed_info.next_closed_hour,
2627
closed_dimension_id_user = closed_info.next_closed_user
27-
FROM LATERAL (
28-
SELECT
28+
FROM (
29+
SELECT DISTINCT ON (f_opened_inner.fact_id)
30+
f_opened_inner.fact_id,
2931
f_closed.action_dimension_id_date as next_closed_date,
3032
f_closed.action_dimension_id_hour_of_week as next_closed_hour,
3133
f_closed.action_dimension_id_user as next_closed_user
32-
FROM dwh.facts f_closed
33-
WHERE f_closed.id_note = f_opened.id_note
34+
FROM dwh.facts f_opened_inner
35+
JOIN dwh.facts f_closed ON (
36+
f_closed.id_note = f_opened_inner.id_note
3437
AND f_closed.action_comment = 'closed'
35-
AND f_closed.action_at > f_opened.action_at
36-
ORDER BY f_closed.action_at ASC
37-
LIMIT 1
38+
AND f_closed.action_at > f_opened_inner.action_at
39+
)
40+
WHERE f_opened_inner.action_comment = 'opened'
41+
AND f_opened_inner.closed_dimension_id_date IS NULL
42+
ORDER BY f_opened_inner.fact_id, f_closed.action_at ASC
3843
) closed_info
39-
WHERE f_opened.action_comment = 'opened'
40-
AND f_opened.closed_dimension_id_date IS NULL;
44+
WHERE f_opened.fact_id = closed_info.fact_id;
4145

4246
-- Verify update
4347
-- Check that opened facts that have a subsequent close action have been updated

0 commit comments

Comments
 (0)