简体   繁体   English

SQL Select ALL ROWS 但仅当列值唯一时

[英]SQL Select ALL ROWS but only if column value is unique

If I do the following:如果我执行以下操作:

select * from myTable

I get:我得到:

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

I want to perform a select statement where I only pull the rows that have a unique number for column 1我想执行一个 select 语句,我只提取第 1 列具有唯一编号的行

In otherwords I am looking for this result:换句话说,我正在寻找这个结果:

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

Not sure exactly how to pull this off with only one statement or if there even is a way to do that.不确定如何仅用一个语句来实现这一点,或者是否有办法做到这一点。 Thanks!谢谢!

You can use aggregation:您可以使用聚合:

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

If there is only one row for a given value of col1 , then max(col2) will be the value of the column on that row.如果col1的给定值只有一行,则max(col2)将是该行上列的值。

If there are not duplicate (column1, column2) tuples, one option is not exists :如果没有重复的(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
)

A simple query to limit column #1 entires w/ a count not equal to 1.一个限制列 #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

you can use group by =你可以使用分组=

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM