我有一张表T1
,如下所示:
COL1 COL2
---------------
aaa 10
bbb 20
bbb 20
bbb 10
ccc 30
ccc 30
aaa 30
ddd 30
我希望col1
和col2
值col1
只映射到一个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);
没有那些内部查询的其他选项是什么。
提前致谢。
答案 0 :(得分:2)
select Col1
, max(Col2) as Col2
from YourTable
group by
Col1
having count(distinct Col2) = 1
having
子句确保单个组中只有一个Col2
。您可以使用max
,min
甚至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