如果我的表中有两列,first_name
并且last_name
我想知道有多少人使用相同的名字,例如:
Name Count | Name
-------------------------
12 | John Smith
8 | Bill Gates
4 | Steve Jobs
按两列分组 - 例如:
select firstname, lastname, count(*) as `Name Count`
from table
group by firstname, lastname
由于名称可以有不同的大小写(即“John”和“john”),并且数据库中可能有多余的空格,所以首先使用一个子查询来清理并连接名字和姓氏,然后使用COUNT
and GROUP BY
:
SELECT COUNT(*) AS `name_count`
FROM (
SELECT CONCAT(LOWER(TRIM(`first_name`)), ' ', LOWER(TRIM(`last_name`))) AS `full_name`
FROM `table`
) AS `table_with_concat_names`
GROUP BY `full_name`
ORDER BY `name_count` DESC;
你会注意到我同时申请LOWER(TRIM())
了名字和姓氏。这样,它们都用 LOWER() 全部小写,这样 'John Smith' 和 'john smith' 在比较时是同一个人,而且我使用 TRIM() 删除多余的空格,所以 'John Smith' (空格后) 和“约翰·史密斯”也是同一个人。
使用 group by 子句
select (firstname + ' ' + lastname) as Name, count(*) as 'Name Count'
from table
group by (firstname + lastname)