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

问题描述 投票:1回答:1

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

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

示例数据

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

我需要选择将输出的:

lastname | firstname | number_of_accounts
Smith    | John      | 2
postgresql
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.