首页 > 解决方案 > 在 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

标签: postgresql

解决方案


尝试这个:

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; 

另一种方法是使用withandself 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 

推荐阅读