获取按 ENUM 字段分组的 COUNT,并用 0 填充未使用的枚举

Get COUNT grouped by ENUM field and fill not used enum with 0

假设我有一个 table

class UserModel(BaseModel):
    id = Column(Integer, primary_key=True)
    status = Column(
        Enum(
            "registered",
            "confirmed",
            "pending",
            name="user_statuses",
        )
    )

我想查询 table 并获取按状态分组的用户数,如果没有具有特定状态的用户,我仍然想 return 它但 0

例如,假设我在数据库中有以下用户:

id    status
1     confirmed
2     confirmed
3     registered

结果我想得到类似的东西:

status     user_count
registered 1
confirmed  2
pending    0

我怎样才能实现这样的目标?

您必须使用内部带有 count() 的子查询。 如果你有 status table(result here):

select s.status, coalesce(u.user_count,0) as user_count
from status s left join 
(select status,count(*) as user_count from users group by status) u on u.status = s.status

如果您没有 status table (result here):

select s.status, coalesce(u.user_count,0) as user_count
from (select unnest(array['registered','confirmed','pending']) as status) s left join 
(select status,count(*) as user_count from users group by status) u on u.status = s.status