postgresql - 如何在满足某些条件时复制某些行,然后在 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
任何帮助将不胜感激。谢谢。
解决方案
尝试这个
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
推荐阅读
- python - 使用 openpyxl 获取工作表的名称
- java - if 语句字节与整数
- object - 在 Logtalk 中将对象保存到文件
- angular - 如何使用量角器打字稿在具有跨度的按钮上单击具有相似元素详细信息的元素
- java - URLEncodedUtils 不解析来自给定 url 的所有获取参数
- java - leetcode 109:将排序列表转换为二叉搜索树
- java - NoClassDefFoundError: org/elasticsearch/script/ScriptEngine
- python - 根据 Python 中的唯一键将列中的类别转换为编码为 1 或 0 的多列
- firebase - 无法在 Firebase 中部署包含 @google-cloud/storage 的功能
- java - 如何使用 Zxing 库对 QR 码扫描仪进行人像?