同时在多个列上选择distinct,并在PostgreSQL中保留一列

时间:2014-11-23 04:30:44

标签: sql postgresql

对于这样的表:

tblA  

A,B,C  
1,2,t3a  
1,3,d4g  
1,2,b5e  
1,3,s6u 

我想生成一个同时在A和B上选择不同的表,并且仍保留一个C值,如下所示:

tblB  

A,B,C  
1,2,t3a  
1,3,d4g 

看起来这很简单,但却找不到我的生活。

DROP TABLE IF EXISTS tblA CASCADE;  
SELECT DISTINCT ON (A,B), C  
INTO tblB  
FROM tblA;  

3 个答案:

答案 0 :(得分:3)

当您使用DISTINCT ON时,您应该ORDER BY

SELECT DISTINCT ON (A,B), C
INTO tblB
FROM tblA
ORDER BY A, B;

答案 1 :(得分:3)

这应该可以解决问题

CREATE TABLE tblB AS (
    SELECT A, B, max(C) AS max_of_C FROM tblA GROUP BY A, B
)

答案 2 :(得分:0)

使用视图执行distinct,然后将其连接到原始表以选择一行C列。插入目标留给您了解。哦,你可以从t中获取多个列,而不仅仅是c - 唯一的一点是你的子查询需要找到一种方法将它限制为只有一行。

create table t (a int, b int, c int);

create view tv as select distinct a, b from t;

insert into t (a, b, c) values(1, 2, 10);
insert into t (a, b, c) values(1, 2, 20);
insert into t (a, b, c) values(1, 3, 30);
insert into t (a, b, c) values(1, 3, 40);

CREATE TABLE tblB AS (
select tv.a, tv.b, t.c  from tv, t
where tv.a = t.a and tv.b = t.b
/* pick smallest ctid which is a unique row id built into postgres */
and t.ctid = (select min(ctid) from t s where s.a = t.a and s.b = t.b);
)