SQL GROUP BY 和 COUNT 条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13003656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:44:00  来源:igfitidea点击:

SQL GROUP BY and a condition on COUNT

sql

提问by CodeGuy

I have the following SQL expression:

我有以下 SQL 表达式:

select id, count(oID) from MyTable group by oID;

and I get something like

我得到类似的东西

+-------+---------------+
| id    | count(oID)    |
+-------+---------------+
|   002 |             6 |
|   104 |             1 |
|   101 |             1 |
|   908 |             1 |
+-------+---------------+

And now I'd like to pull out the rows (select id) where count(oID)is 1. How can I do this in one SQL statement?

现在我想拉出行 (select id) where count(oID)is 1. 我怎样才能在一个 SQL 语句中做到这一点?

回答by John Woo

Use a HAVINGclause to filter an aggregated column.

使用HAVING子句过滤聚合列。

SELECT   id, count(oID) 
FROM     MyTable 
GROUP BY oID 
HAVING   count(oID) = 1

UPDATE 1

更新 1

wrap the results in a subquery

将结果包装在子查询中

SELECT a.*
FROM tableName a INNER JOIN
    (
        SELECT   id 
        FROM     MyTable 
        GROUP BY id  
        HAVING   count(oID) = 1
    ) b ON a.ID = b.ID