sql选择所有行,但仅当列值唯一时

bbuxkriu  于 2021-07-24  发布在  Java
关注(0)|答案(5)|浏览(472)

如果我做了以下事情:

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

我不知道如何用一句话来完成这件事,或者是否有办法做到这一点。谢谢!

sg3maiej

sg3maiej1#

如果没有重复 (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
)
h9a6wy2h

h9a6wy2h2#

可以使用聚合:

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

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

sc4hvdpw

sc4hvdpw3#

一个简单的查询,用于限制列#1 entires w/a count not等于1。

SELECT col1, COUNT(col1), col2 
FROM myTable
WHERE count(col1) = 1
GROUP BY col1
kpbpu008

kpbpu0084#

Select column1, column2 from (select column1, column2, count(column1) over (PARTITION BY column2) count
from myTable) where count = 1
vuktfyat

vuktfyat5#

您可以使用分组方式=

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

相关问题