开发者

How can I count unique pairs of values in SQL?

开发者 https://www.devze.com 2023-03-03 22:57 出处:网络
With the following sql statement I can get all unique values with their counts for a given column: select column, count(column) as count

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 开发者_如何学Cassume whatever solution you come up with should be translatable to any db.


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;


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


Use multiple columns in your group by clause.

select first_name, last_name, count(*) as count from table group by first_name, last_name


SELECT first_name, last_name, COUNT(distinct last_name) AS c
FROM ttable
GROUP BY first_name, last_name
HAVING c > 999
ORDER BY c DESC 

Adding distinct will do it in MYSQL. Thanks

0

精彩评论

暂无评论...
验证码 换一张
取 消