[英]How should we count the number of distinct pairs / tuples in SQL?
Suppose the schema is like this: 假设架构是这样的:
First Name | Last Name | Age | ID
====================================
John Smith 18 123
John Smith 21 234
John Smith 19 123
Cathy Zhang 20 144
Cathy Zhang 20 144
Jackie Chan 35 456
Suppose I want to count the number of distinct pairs after each (first name, last name). 假设我想计算每个(名字,姓氏)之后的不同对的数量。 So that the output should be: 所以输出应该是:
John Smith 3
Cathy Zhang 1
Jackie Chan 1
I think I can first do: 我想我可以先做:
SELECT FirstName,LastName,Age,ID,COUNT(*);
And then 然后
SELECT FirstName,LastName,COUNT(*)
Is there a better approach? 有更好的方法吗?
To return the count of each distinct firstname lastname, you would use COUNT
and GROUP BY
: 要返回每个不同的firstname lastname的计数,您将使用COUNT
和GROUP BY
:
SELECT FirstName, LastName, COUNT(*)
FROM TableName
GROUP BY FirstName, LastName
In your above example, I think you meant Zhang to have a count of 2 though. 在上面的例子中,我认为你的意思是张的计数为2。
--EDIT - 编辑
If I'm understanding your latest comment correctly, you want to also use DISTINCT
: 如果我正确理解您的最新评论,您还想使用DISTINCT
:
SELECT FirstName, LastName, Age, Id, COUNT(*)
FROM (SELECT DISTINCT FirstName, LastName, Age, Id FROM TableName) T
GROUP BY FirstName, LastName, Age, Id
Good luck. 祝好运。
Please try: 请试试:
SELECT
FirstName,
LastName,
COUNT(*)
FROM (
SELECT DISTINCT * FROM YourTable
) X
GROUP BY FirstName, LastName
试试用,
SELECT firstName, lastName, count(1) FROM name_tab GROUP BY firstName, lastName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.