Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count unique pairs of values in SQL?

Tags:

With the following sql statement I can get all unique values with their counts for a given column:

select column, count(column) as count           from table group by column order by count desc; 

How would I get all unique pairs of values with counts. For instance if I had a table of with columns first_name and last_name, I might find results something like this:

first_name | last_name | count

John | Smith | 42

John | Johnson | 39

David | Smith | 37

etc...

Can I do this in basic SQL? I generally use MySQL, but I assume whatever solution you come up with should be translatable to any db.

like image 252
Jay Askren Avatar asked May 06 '11 12:05

Jay Askren


People also ask

Can I count two columns in SQL?

You can use CASE statement to count two different columns in a single query. To understand the concept, let us first create a table.


2 Answers

You've almost got it correct... You just add an additional GROUP BY column like so:

SELECT [first_name], [last_name], COUNT(*) AS [Count]  FROM [Table] GROUP BY [first_name], [last_name] ORDER BY [Count] DESC; 
like image 186
Ryan Avatar answered Sep 22 '22 22:09

Ryan


If you just want the count of how many distinct pairs, you could do this more simply. A GROUP BY clause is not necessary.

SELECT COUNT(DISTINCT first_name, last_name) AS count_names FROM Table 
like image 32
adam Avatar answered Sep 22 '22 22:09

adam