Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query, count and group by

Tags:

If I have data like this:

Key Name
1 Dan
2 Tom
3 Jon
4 Tom
5 Sam
6 Dan

What is the SQL query to bring back the records where Name is repeated 2 or more times?

So the result I would want is

Tom
Dan
like image 307
Dan Avatar asked Aug 06 '08 09:08

Dan


People also ask

Can we use GROUP BY and count together in SQL?

We can use GROUP BY to group together rows that have the same value in the Animal column, while using COUNT() to find out how many ID's we have in each group. It returns a table with three rows (one for each distinct animal).

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.

How do I count rows in SQL by group?

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.

How do I SELECT a column and a count in SQL?

Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table. COUNT(column_name) will not include NULL values as part of the count.


2 Answers

Couldn't be simpler...

Select Name, Count(Name) As Count      From Table     Group By Name     Having Count(Name) > 1     Order By Count(Name) Desc 

This could also be extended to delete duplicates:

Delete From Table Where Key In (     Select Max(Key)         From Table         Group By Name         Having Count(Name) > 1     ) 
like image 149
GateKiller Avatar answered Sep 17 '22 14:09

GateKiller


select name from table group by name having count(name) > 1 
like image 23
Ryan Avatar answered Sep 20 '22 14:09

Ryan