Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL GROUP BY and a condition on COUNT

Tags:

sql

I have the following SQL expression:

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?

like image 424
CodeGuy Avatar asked Oct 22 '12 00:10

CodeGuy


People also ask

Can we use GROUP BY and count together in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Can I put condition in count in SQL?

COUNT() with HAVINGThe HAVING clause with SQL COUNT() function can be used to set a condition with the select statement.

How do I count after GROUP BY in SQL?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.


1 Answers

Use a HAVING clause to filter an aggregated column.

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

UPDATE 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
like image 188
John Woo Avatar answered Oct 20 '22 17:10

John Woo