Skip to content

Commit

Permalink
WIP - Simple average SQL
Browse files Browse the repository at this point in the history
  • Loading branch information
aaron-contreras committed Sep 23, 2024
1 parent 424a2b8 commit bc12c60
Showing 1 changed file with 92 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,98 @@ def update_to_work_weighted_average
end

def update_to_simple_average
### Test SQL
<<~SQL.squish
DROP TABLE IF EXISTS TEMP_WP_PROGRESS_VALUES;
DROP TABLE IF EXISTS TEMP_WORK_PACKAGE_DEPTH;
CREATE UNLOGGED TABLE TEMP_WP_PROGRESS_VALUES AS
SELECT
ID,
PARENT_ID,
STATUS_ID,
DONE_RATIO,
NULL::INTEGER AS DERIVED_DONE_RATIO
FROM
WORK_PACKAGES;
-- Create a temporary table to store depths
WITH RECURSIVE
WORK_PACKAGE_DEPTH AS (
-- Base case: Leaves (work packages with no children)
SELECT
WP.ID,
WP.PARENT_ID,
0 AS DEPTH
FROM
TEMP_WP_PROGRESS_VALUES WP
WHERE
NOT EXISTS (
SELECT
1
FROM
TEMP_WP_PROGRESS_VALUES C
WHERE
C.PARENT_ID = WP.ID
)
UNION ALL
-- Recursive case: Parents
SELECT
WP.PARENT_ID AS ID,
WP2.PARENT_ID,
WPD.DEPTH + 1 AS DEPTH
FROM
WORK_PACKAGES WP
INNER JOIN WORK_PACKAGE_DEPTH WPD ON WP.ID = WPD.ID
INNER JOIN TEMP_WP_PROGRESS_VALUES WP2 ON WP.PARENT_ID = WP2.ID
WHERE
WP.PARENT_ID IS NOT NULL
)
SELECT
ID,
DEPTH INTO TEMPORARY TABLE TEMP_WORK_PACKAGE_DEPTH
FROM
WORK_PACKAGE_DEPTH;
DO $$
DECLARE
min_depth INTEGER := 0;
max_depth INTEGER := (SELECT MAX(depth) FROM temp_work_package_depth);
current_depth INTEGER := min_depth;
BEGIN
WHILE current_depth <= max_depth LOOP
UPDATE TEMP_WP_PROGRESS_VALUES wp
SET derived_done_ratio =#{' '}
CASE
WHEN current_depth = min_depth
THEN
NULL
ELSE
ROUND(
(
COALESCE(wp.done_ratio, 0) +
(
SELECT SUM(COALESCE(child_wp.derived_done_ratio, child_wp.done_ratio, 0))
FROM TEMP_WP_PROGRESS_VALUES child_wp
WHERE child_wp.parent_id = wp.id
)
) / (
CASE WHEN wp.done_ratio IS NOT NULL THEN 1 ELSE 0 END +
(SELECT COUNT(1) FROM TEMP_WP_PROGRESS_VALUES child_wp WHERE child_wp.parent_id = wp.id)
)
)
END
WHERE wp.id IN (
SELECT id FROM temp_work_package_depth WHERE depth = current_depth
);
current_depth := current_depth + 1;
END LOOP;
END $$;
SQL

execute(<<~SQL.squish)
UPDATE temp_wp_progress_values
SET derived_done_ratio = CASE
Expand Down

0 comments on commit bc12c60

Please sign in to comment.