首页 > 解决方案 > 如何在满足某些条件时复制某些行,然后在 PostgreSQL 中更新其某些列值?

问题描述

假设我有一个飞行记录数据样本,其中“类型”列的值为 1 或 2(1 表示单程,2 表示往返):

customer_id, origin, destination, type
1111, London, Munchen, 2
2222, Rome, Paris, 1

我想复制“类型”值为 2 的某些记录,然后交换复制记录的“来源”和“目的地”列的值,并将“类型”列的值都更改为 1。

所需的输出是这样的:

customer_id, origin, destination, type
1111, London, Munchen, 1
1111, Munchen, London, 1
2222, Rome, Paris, 1

任何帮助将不胜感激。谢谢。

标签: postgresql

解决方案


尝试这个

WITH update_list AS
(
UPDATE your_table
SET type = 1
WHERE type = 2
RETURNING customer_id, origin, destination
)
INSERT INTO your_table (customer_id, origin, destination, type)
SELECT l.customer_id, l.destination, l.origin, 1
FROM update_list AS l

推荐阅读