sql - 连接两个表时如何选择其中一个有条件的两列?
问题描述
我有两张桌子:
表 #1:所有用户
- 用户身份
- 部
- 状态(0 或 1)
- 在线
表#2:用户日志
- 用户登录
- 登录时间
我想加入两个这样的表:
(按部门分组)
- 部
- 计数(*)==>所有用户
- 计数(*)==> 状态= 1
- 计数(*)==> table1.userid=table2.userlogid
我不知道如何显示关于 count(*)==> status= 1 的列
我无法对“count(*)==> status=1”的列进行分组
请帮我检查我的代码
select o.department as DM,
count(p.userlogid) as userlog,
count(o.department) as alluser,
count(p.userlogid) as userlog1
from table2 as p
right OUTER join table1 as o
on p.userlogid=o.USERID
on q.userlogid=o.userid
where o.status=1
group by o.department;
解决方案
看看这个查询:
select o.department as DM,
sum(1) allusers,
sum(case when status=1 then 1 else 0 end) usersWithStatus1,
from table2 as p
right OUTER join table1 as o
on p.userlogid=o.USERID
GROUP BY o.department;
您使用SUM
withCASE
来执行某些条件。
推荐阅读
- django - Django 值错误“视图 capstone.views.home 没有返回 HttpResponse 对象。它返回了 None。”
- python - 如何模拟数据类
- amazon-web-services - 使用 CloudFormation 为现有 EFS 创建 EFS 接入点
- apache - 在 Ubuntu 20.04 服务器上为 Jitsi Meet 安装 LetsEncript SSL 时出错
- unreal-engine5 - 我在使用 Epic 游戏和虚幻引擎时遇到问题。特别是我的项目没有出现
- reactjs - 为什么 Internet 在 React 预览链接上不起作用?
- javascript - 如何使用自定义匹配器通过多个搜索字符串进行 select2 过滤?
- swift - 如果另一个标签占用 X 行,我该如何隐藏一个标签?
- google-sheets - 谷歌表格动态复制/粘贴
- reactjs - 从 ReactJs 中的图像文件中读取条形码