按联接分组查询

时间:2021-02-02 17:51:10

标签: sql oracle

我的数据库中有两个表:

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

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

像这样:

<头>
类型 type_count status_3_count
type1 4 2
type2 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

2 个答案:

答案 0 :(得分:1)

您可以使用 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

答案 1 :(得分:0)

您可以按如下方式使用条件聚合:

select a.type, count(*) type_count, 
       count(case when status = 3 then 1 end) status_3_count
    from applications a
    join statuses b on b.id = a.status_id and b.id = 3
Group by a.type
相关问题