首页 > 解决方案 > 连接两个表时如何选择其中一个有条件的两列?

问题描述

我有两张桌子:

表 #1:所有用户

表#2:用户日志

我想加入两个这样的表:

(按部门分组)

我不知道如何显示关于 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;

标签: sqlsql-server

解决方案


看看这个查询:

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;

您使用SUMwithCASE来执行某些条件。


推荐阅读