SQL GROUP BY和COUNT上的条件

时间:2012-10-22 00:38:06

标签: sql

我有以下SQL表达式:

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

我得到像

这样的东西
+-------+---------------+
| id    | count(oID)    |
+-------+---------------+
|   002 |             6 |
|   104 |             1 |
|   101 |             1 |
|   908 |             1 |
+-------+---------------+

现在我想提取count(oID)为1的行(选择id)。如何在一个SQL语句中执行此操作?

1 个答案:

答案 0 :(得分:17)

使用HAVING子句过滤聚合列。

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

更新1

将结果包装在子查询中

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