postgresql - 在 Postgresql 中将 2 行合并为 1 行
问题描述
我有这张桌子:
CREATE TABLE mytable
(
id integer NOT NULL,
rank integer,
col1 text,
col2 text,
CONSTRAINT mytable_pk PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
INSERT INTO mytable(id, rank, col1, col2) VALUES (1, 1, 'c', 'c');
INSERT INTO mytable(id, rank, col1, col2) VALUES (2, 2, 'a', 'a');
INSERT INTO mytable(id, rank, col1, col2) VALUES (3, 2, 'b', NULL);
INSERT INTO mytable(id, rank, col1, col2) VALUES (4, 3, 'c', 'c');
我必须在 postgresql 9.0 中执行一个查询,将具有相等“rank”值的两行“合并”在一行中,使用以下规则:对于 col1 和 col2,选择具有更高“id”值的值,但是当这是 NULL , 选择其他值(注意:“rank”值相等的行不能超过 2)
预期结果:
rank col1 col2
------------------------------
1 c c
2 b a
3 c c
解决方案
尝试这个:
select mt.rank,
(select col1 from mytable where id = max(case when mt.col1 is not null then mt.id end)) as col1,
(select col2 from mytable where id =max(case when mt.col2 is not null then mt.id end)) as col2
from mytable mt
group by mt.rank
order by mt.rank;
另一种方法是使用with
andself join
with tab as (select rank,
max(case when col1 is not null then id end) col1,
max(case when col2 is not null then id end) col2 from mytable
group by rank)
select tab.rank "rank", mt1.col1 "col1", mt2.col2 "col2"
from tab
left join mytable mt1 on mt1.id=tab.col1
left join mytable mt2 on mt2.id=tab.col2
order by tab.rank
推荐阅读
- r - RColorbrewer scale_fill_brewer 在图例键周围加上括号
- hadoop - Hive 分区方案及其对性能的影响
- r - 用“|”分割我的数据框中的字符向量 不工作
- javascript - Trying to understand how `${c}` in this string interpolation points to the elements in an array
- flutter - Flutter web get screen size
- kerberos - Keycloak:是否需要 MIT Kerberos 客户端?
- angular - Angular 构建中何时生成 index.html?
- python - 打开目录并读取不同的文件并将它们保存到不同的变量中,Python
- python - 编写和运行 DAG 任务的最简洁方法是什么?
- javascript - 选择值在jQuery中返回null