我正在尝试从我的数据库中找到有多个帐户的用户。每个用户都有姓氏和名字属性。
如何列出具有相同名字和姓氏的所有用户?
示例数据
id | lastname | firstname
1 | Smith | John
2 | Smith | John
3 | McDonald | Ronald
我需要选择将输出的:
lastname | firstname | number_of_accounts
Smith | John | 2
使用count(*)
和group by:
select lastname, firstname, count(*)
from my_table
group by lastname, firstname;
lastname | firstname | count
----------+-----------+-------
McDonald | Ronald | 1
Smith | John | 2
(2 rows)
您可以使用having
子句过滤结果:
select lastname, firstname, count(*)
from my_table
group by lastname, firstname
having count(*) > 1;
lastname | firstname | count
----------+-----------+-------
Smith | John | 2
(1 row)