查询以获取表中的行,其中第1列中的值仅映射到第2列中的一个值

时间:2013-11-05 08:37:19

标签: sql oracle

我有一张表T1,如下所示:

COL1  COL2                   
---------------
aaa   10 
bbb   20                     
bbb   20                     
bbb   10                     
ccc   30                     
ccc   30                     
aaa   30                     
ddd   30                     

我希望col1col2col1只映射到一个col2

COL1 COL2                   
-----------
ccc 30                     
ddd 30    

请告诉我如何实现目标。

我尝试使用以下内容来获取所需的结果集:

select distinct col1, col2 
 from t1 
where col1 in (select col1 
                 from (select distinct col1, col2 from t1) 
                group by col1 
               having count(col2) = 1);

没有那些内部查询的其他选项是什么。

提前致谢。

2 个答案:

答案 0 :(得分:2)

select  Col1
,       max(Col2) as Col2
from    YourTable
group by
        Col1
having  count(distinct Col2) = 1

having子句确保单个组中只有一个Col2。您可以使用maxmin甚至avg来显示它。

working at SQL Fiddle(感谢Amit Singh。)

答案 1 :(得分:1)

Select Distinct A.Col1,A.Col2 from Table1 A
inner join 
(Select Col1,Count(Distinct Col2) as col3 from Table1 group by Col1) B on
A.Col1=B.Col1 and B.Col3=1

Sql Fiddle