我在PostgreSQL中有一张表,在某些情况下,我会得到重复的条目,并且我想将它们合并到一个表中。起初,我不想使用临时表,而我的第一个方法是使用此表。
WITH duplicate_entries AS (
SELECT group_id, month, count(*)
FROM table_a
GROUP BY 1,2
HAVING COUNT(*) > 1
), new_entries as(
SELECT f.group_id , f.month , max(a) , max(b), sum(c) ....
FROM table_a f
JOIN duplicate_entries d ON f.group_id = d.group_id AND f.month = d.month
GROUP BY 1,2
), delete_duplicate_entries as (
DELETE
FROM table_a f
USING duplicate_entries e
WHERE f.group_id = e.group_id and f.month = e.month
)INSERT INTO table_a(group_id, month, a, b, c, d)
SELECT grou_id , month, a, b, c, d
FROM new_entries;
但是当我向同事展示时,他们对此不太满意,因此我最终使用了一张临时桌子。我的问题是,以上代码是否错误,并且出于某种原因应避免使用?