SQL Select 所有行,但前提是列值是唯一的

SQL Select ALL ROWS but only if column value is unique

如果我执行以下操作:

select * from myTable

我得到:

Column 1  | Column 2
---------------------
1         | Create
1         | Delete
2         | Create
3         | Create
4         | Create
4         | Delete
5         | Create

我想执行 select 语句,我只提取第 1 列具有唯一编号的行

换句话说,我正在寻找这个结果:

Column 1  | Column 2
---------------------
2         | Create
3         | Create
5         | Create

不确定如何只用一个语句来实现这一点,或者是否有办法做到这一点。谢谢!

您可以使用聚合:

select col1, max(col2) as col2
from t
group by col1
having count(*) = 1;

如果 col1 的给定值只有一行,则 max(col2) 将是该行上列的值。

如果没有重复的 (column1, column2) 元组,一种选择是 not exists:

select t.*
from mytable t
where not exists (
    select 1 from mytable t1 where t1.column1 = t.column1 and t1.column2 <> t.column2
)

一个简单的查询来限制第 1 列的计数不等于 1。

SELECT col1, COUNT(col1), col2 
FROM myTable
WHERE count(col1) = 1
GROUP BY col1
Select column1, column2 from (select column1, column2, count(column1) over (PARTITION BY column2) count
from myTable) where count = 1

你可以使用 group by =

select * from myTable where empno in (select empno val from myTable group by empno having COUNT(*) =1 )