我试图从我的数据库中找到拥有多个帐户的用户。每个用户都有姓氏和名字属性。
如何列出所有具有相同名字和姓氏的用户?
示例数据
id | lastname | firstname
1 | Smith | John
2 | Smith | John
3 | McDonald | Ronald
我需要选择输出:
lastname | firstname | number_of_accounts
Smith | John | 2
答案 0 :(得分:1)
使用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)