WITH prepared AS (
SELECT
issue_task_id,
MAX(stage_id) AS stage_id,
MAX(executor_id) AS executor_id,
MAX(day_id) day_id,
MAX(project_id) project_id,
MAX(area_id) area_id,
MAX(state_id) state_id,
MAX(location_id) location_id,
MAX(week_id) week_id,
MAX(repair_type_id) repair_type_id,
MAX(danger_id) danger_id,
MAX(country_id) country_id,
MAX(region_id) region_id,
MAX(city_id) city_id,
MAX(place_id) place_id,
MAX(ruad_id) ruad_id,
MAX(CASE WHEN md_measure_id = '1'
THEN value END) AS area,
MAX(CASE WHEN md_measure_id = '2'
THEN value END) AS length,
MAX(CASE WHEN md_measure_id = '4'
THEN value END) AS depth,
0
FROM f_road
GROUP BY issue_task_id, stage_id
)
INSERT INTO snapshot_road (issue_task_id, stage_id, executor_id, day_id, project_id, area_id, state_id, location_id,
week_id, repair_type_id, danger_id, country_id, region_id, city_id, place_id, ruad_id,
area, length, depth, actuality) SELECT *
FROM prepared;
WITH ranked AS (
SELECT
rank()
OVER (PARTITION BY issue_task_id
ORDER BY stage_id DESC) AS rnk,
id
FROM snapshot_road
), pre AS (
SELECT id
FROM ranked
WHERE rnk = 1
)
UPDATE snapshot_road
SET actuality = 1 FROM pre
WHERE pre.id = snapshot_road.id
WITH pre AS (
SELECT
issue_task_id,
stage_id,
area,
length,
depth,
rank()
OVER (PARTITION BY issue_task_id
ORDER BY stage_id DESC)
FROM snapshot_road
WHERE area IS NOT NULL AND actuality = 0
ORDER BY id
), last_tasks AS (
SELECT
issue_task_id,
area,
length,
depth
FROM pre
WHERE rank = 1
)
UPDATE snapshot_road
SET area = last_tasks.area, length = last_tasks.length, depth = last_tasks.depth FROM last_tasks
WHERE snapshot_road.issue_task_id = last_tasks.issue_task_id
AND snapshot_road.area IS NULL