SQL / Oracle仅在第二列中返回具有相同值的字段

时间:2018-08-13 16:19:29

标签: sql oracle

仅当在重复日志的第二列中找到相同的值时才需要返回列1。如果看到其他任何值,则从结果中排除。

A   2
A   2
A   2
A   2
A   2

排除

B   2
B   1
B   2
B   3
B   2


 select b. column1 
    from 
    ( select * 
      from table 
      where column2 != 1

    ) b
  where b.column2 = 2 

结果:

A

3 个答案:

答案 0 :(得分:2)

您可以使用聚合和HAVING

SELECT col1
FROM tab
GROUP BY col1
HAVING COUNT(DISTINCT col2) = 1;

或者如果您需要原始行:

SELECT s.*
FROM (SELECT t.*, COUNT(DISTINCT col2) OVER(PARTITION BY col1) AS cnt
      FROM tab t) s
WHERE s.cnt = 1;

答案 1 :(得分:1)

如果您需要原始行,我建议not exists

select t.*
from t
where not exists (select 1 from t t2 where t2.col1 = t.col1 and t2.col2 <> t.col2);

如果您只想要col1值(这对我来说很有意义),那么我可以将聚合表达为:

select col1
from t
group by col1
having min(col2) = max(col2);

如果要将“ all-null”作为有效选项包括在内,则:

having min(col2) = max(col2) or min(col2) is null

答案 2 :(得分:-1)

尝试此查询

select column1 from (select column1,column2 from Test group by column1,column2) a group by column1 having count(column1)=1;