我的数据库中有两个表:
我想按类型分组以获取每种类型的计数,然后作为第三列我想获取该计数中有多少个 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
答案 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