我想从postgresql中的一个表中返回记录,当第1列中的一个不同值在第2列中分布在多个记录上时.
举个简单的例子:
表1:
column1 - column2
1 – 1
1 – 2
2 – 1
2 – 1
3 - 3
4 - 5
返回:
1 - 1
1 - 2
有很多例子显示不同(例如这个),但我寻找非不同.
select distinct (column2, column1) my_distinct from table1;
我想从postgresql中的一个表中返回记录,当第1列中的一个不同值在第2列中分布在多个记录上时.
举个简单的例子:
表1:
column1 - column2
1 – 1
1 – 2
2 – 1
2 – 1
3 - 3
4 - 5
返回:
1 - 1
1 - 2
有很多例子显示不同(例如这个),但我寻找非不同.
select distinct (column2, column1) my_distinct from table1;
这是一种很普通的方法,只是存在一个来判断那些在同一个列1的列2上有不同值的记录.
菲德尔:https://dbfiddle.uk/Zf9vTS9K
CREATE TABLE t (
column1 INTEGER,
column2 INTEGER
);
INSERT INTO t
(column1, column2)
VALUES
(1, 1),
(1, 2),
(2, 1),
(2, 1),
(3, 3),
(4, 5);
select *
from t t1
where exists
(
select 1
from t t2
where t1.column1 = t2.column1
and t1.column2 <> t2.column2
);