按Value1的Sql Group,其count(*)> 1但具有不同的值2

时间:2018-07-13 21:40:44

标签: sql postgresql psql

给出这样的SQL表

id   value1 value2
---------------
1     1    1
2     1    1
3     1    1
4     2    1
5     2    2
6     3    1

我要查找所有具有重复的value1的value1(即通过具有count(*)> 1的组来使用),但前提是它们的value2具有不同的值

因此在此示例中,我只想返回 2

我正在使用Postgres

2 个答案:

答案 0 :(得分:2)

如果我理解正确,那么这是group by,带有having子句:

select value1
from t
group by value1
having min(value2) <> max(value2) 

答案 1 :(得分:0)

使用

select * from ( select * , ROW_NUMBER() OVER(PARTITION BY Value1  ORDER BY Value1 , Value2 ASC) AS RowValue1, ROW_NUMBER() OVER(PARTITION BY Value1 , Value2 ORDER BY Value1 , Value2 ASC) AS RowValue2 from Table_1 ) As TableTmp where TableTmp.RowValue1 <> TableTmp.RowValue2 

select * from Table_1 where value1 in (select value1 from Table_1 group by value1 having min(value2) <> max(value2) )