我的 PSQL 视图中有三个外部标识符。我怎样才能根据它们的共同 first_id 用third_id 值替换 NULL second_id 值?
目前:
first_id | second_id | third_id
----------+-----------+----------
1 | | 11
1 | | 11
1 | | 11
1 | 22 | 22
2 | 33 | 33
3 | 44 | 44
4 | 55 | 55
5 | 66 | 66
6 | | 77
6 | | 77
6 | | 77
6 | | 77
6 | 88 | 88
应该:
first_id | second_id | third_id
----------+-----------+----------
1 | 22 | 11
1 | 22 | 11
1 | 22 | 11
1 | 22 | 22
2 | 33 | 33
3 | 44 | 44
4 | 55 | 55
5 | 66 | 66
6 | 88 | 77
6 | 88 | 77
6 | 88 | 77
6 | 88 | 77
6 | 88 | 88
我怎样才能做出这种改变?
非常感谢。对此,我真的非常感激。
该second_id确实是一个CASE WHEN的修改third_id。此修改是在视图中进行的。
看法:
first_id | second_id | third_id
----------+-----------+----------
1 | | 11
1 | | 11
1 | | 11
1 | 22 | 22
2 | 33 | 33
3 | 44 | 44
4 | 55 | 55
5 | 66 | 66
6 | | 77
6 | | 77
6 | | 77
6 | | 77
6 | 88 | 88
这是视图使用的表定义 (my_table) 的链接。
https://gist.github.com/dankreiger/376f6545a0acff19536d
再次感谢你的帮助。
您不能使用UPDATE基础表,my_table因为它没有second_id列,因此您应该使视图按照您想要的方式显示数据。对于 CTE,这相当简单:
CREATE VIEW my_view AS
WITH second (first, id) AS (
SELECT first_id, third_id
FROM my_table
WHERE t.localization_key = 'rq.bkd')
SELECT
row_number() OVER (PARTITION BY t.first_id) AS row_number,
t.first_id,
s.id AS second_id,
t.third_id,
t.first_type,
CASE
WHEN t.localization_key = 'rq.bkd' THEN t.created_at
END AS date_1,
CASE
WHEN t.localization_key = 'st.appt' THEN t.created_at
END AS date_2,
CASE
WHEN t.localization_key = 'st.eta' THEN t.created_at
END AS date_3
FROM my_table t
JOIN second s ON s.first = t.first_id
WHERE (t.localization_key = 'rq.bkd'
OR t.localization_key = 'st.appt'
OR t.localization_key = 'st.eta')
AND t.first_type = 'thing'
ORDER BY t.created_at DESC;
Run Code Online (Sandbox Code Playgroud)
这假设my_table.localization_key = 'rq.bkd'您确实有 1 个third_id值;如果没有,您应该添加适当的限定符,例如ORDER BY first_id ASC NULLS LAST LIMIT 1或其他一些合适的过滤器。另请注意,CTE 是JOINed,而不是LEFT JOINed,假设始终存在一个(first_id, third_id)不带NULLs 的有效对。
| 归档时间: |
|
| 查看次数: |
2673 次 |
| 最近记录: |