首页 > 解决方案 > 通过连接分组查询

问题描述

我的数据库中有两个表:

  1. 应用程序(id、类型、user_id、status_id)。
  2. 状态(id,名称);

我想按类型分组以获取每种类型的计数,然后作为第三列,我想获取该计数中有多少 status_id 为 3

像这样的东西:

类型 type_count status_3_count
类型1 4 2
类型2 10 5

我试过这个,但它不起作用。

select a.type, count(*) type_count, count(b.id) status_3_count
    from applications a
    join statuses b on b.id = a.status_id and b.id = 3
    group by a.type, b.id

标签: sqloracle

解决方案


您可以从应用程序表中通过 group by 获取所有这些信息。请尝试以下查询:

select type,count(*) type_count,sum(case when status_id=3 then 1 else 0 end)status_3_count
from applications 
group by type

推荐阅读