返回一个字段中没有重复项的记录

时间:2018-02-14 15:28:28

标签: sql oracle plsql

我有以下(示例)脚本

Select field1, field2, field3, field4, field5 from tblsample

可能会返回

field1, field2, field3, field4, field5
123     etc     etc     etc     etc
123     etc     etc     etc     etc
123     etc     etc     etc     etc
456     etc     etc     etc     etc
789     etc     etc     etc     etc
789     etc     etc     etc     etc
125     etc     etc     etc     etc

如何编写查询以仅返回“字段1”中没有重复值的行。例如,对于上面的表格,预期结果是:

field1, field2, field3, field4, field5
456     etc     etc     etc     etc
125     etc     etc     etc     etc

请注意,123和789的行不包含在结果中,因为有多行包含这些值。

5 个答案:

答案 0 :(得分:1)

在这种情况下使用分析count()

<强> demo

select field1, field2, field3, field4, field5
  from (select field1, field2, field3, field4, field5, 
               count(1) over (partition by field1) cnt
          from tblsample)
  where cnt = 1

答案 1 :(得分:0)

Select field1, max( field2), max(field3), max(field4), max( 
 field5)
 from tblsample
group by field1
having count(*) = 1;

答案 2 :(得分:0)

不使用max()函数;

select *
from tblsample
where field1 in 
(select field1 
 from tblsample 
 group by field1 
 having count(1)=1);

答案 3 :(得分:0)

select * 
from (select *,COUNT(*) over (partition by field1) row 
from tblsample) x 
where row = 1

答案 4 :(得分:0)

不使用窗口功能:

SELECT *
 FROM tblsample t INNER JOIN (SELECT
                            count(field1),
                            field1
                          FROM tblsample
                          GROUP BY field1
                          HAVING count(field1) = 1) a
ON a.field1 = t.field1