Postgres:选择具有多个帐户的用户

时间:2017-12-16 11:21:14

标签: postgresql

我试图从我的数据库中找到拥有多个帐户的用户。每个用户都有姓氏和名字属性。

如何列出所有具有相同名字和姓氏的用户?

示例数据

id | lastname   | firstname
1  | Smith      | John
2  | Smith      | John
3  | McDonald   | Ronald

我需要选择输出:

lastname | firstname | number_of_accounts
Smith    | John      | 2

1 个答案:

答案 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)