sql - 通过连接分组查询
问题描述
我的数据库中有两个表:
- 应用程序(id、类型、user_id、status_id)。
- 状态(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
解决方案
您可以从应用程序表中通过 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
推荐阅读
- jquery - 当网站缩小/处于移动模式时,如何在引导程序 4 中放置 2 个 div 的内容?
- html - 试图让 {% include header.html %} 提示起作用
- google-apps-script - 如何修复错误“异常:您无权调用 DriveApp.getFiles。所需权限:”
- java - 当我拍照时,它会逆时针旋转 90 度
- linux - Bash Script cd 命令截断目录名称
- linux - 在 VSCode linux 中自定义默认设置。(启用曲线)
- javascript - Vue:使用数据来控制 DOM(但 v-for、v-if、v-model 和 v-show 还不够)
- python - 如何让我的 Python 代码表现得像 arduino 串行监视器?
- react-native - 使用钩子将变量添加到状态
- java - SessionFactory opensession 抛出空指针异常