2015-10-01 165 views
0

我有大量的数据。为了解释这一问题,可以考虑这款超最小的一组数据:用于从另一列有不同值的列中选择不同值的SQL

id  col1 col2 
------------------- 
1  ab  12 
2  ab  12 
3  ab  12 
4  cd  34 
5  cd  43 
6  ef  34 
7  ef  56 
8  ef  34 

我需要的是col1选择所有不同值,其中有在col2多个值。因此,从上述结果会是这样的:

col1 
---- 
cd 
ef 

甚至更​​好,在col2为每个唯一对应值的行:

col1 col2 
------------ 
ab  12 
cd  34 
cd  43 
ef  34 
ef  56 

回答

1

您可以用group byhaving做到这一点:

select col2 
from t 
group by col2 
having min(col2) <> max(col2); 

如果你只是想在不同的值,使用select distinct

select distinct col1, col2 
from t; 
+0

谢谢! 'group by'和'having'是SQL的两个部分,我不太熟悉,但它现在完全合理。 –

1

首先之一,返回具有至少两个不同COL2值COL1值:

select col1 from 
tablename 
group by col1 
having count(distinct col2) >= 2 

其次,COL2返回COL1,当COL1具有至少两个不同COL2值:

select * from tablename 
where col1 in (
    select col1 from 
    tablename 
    group by col1 
    having count(distinct col2) >= 2) 
相关问题