如何在连接两个表时选择其中之一具有条件的两列?

时间:2019-06-27 09:19:24

标签: sql sql-server

我有两个表:

表1:所有用户

  • 用户名
  • 部门
  • 状态(0或1)
  • is_online

表#2:用户日志

  • userlogid
  • 登录时间

我想像这样联接两个表:

(按部门分组)

  • 部门
  • count(*)==>所有用户
  • count(*)==> status = 1
  • count(*)==> 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;

2 个答案:

答案 0 :(得分:0)

看看这个查询:

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;

为了执行某些条件,您将SUMCASE一起使用。

答案 1 :(得分:0)

我认为您只需要条件聚合。但我建议您使用$(document).ready(function () { $(window).bind('scroll', function () { var navHeight = $(".header1").height(); ($(window).scrollTop() > navHeight) ? $('.afterLgnRow').addClass('goToTop') : $('.afterLgnRow').removeClass('goToTop'); }); }); $('.afterLgnRow').affix({ offset: { top: $('#header1').offset().top } }); 而不是left join

然后,我认为您想right join来统计用户而不是记录日志:

count(distinct)

您可能想统计日志记录而不是用户。如果是这样,您可以删除select u.department as DM, count(distinct u.userid) as num_users, count(distinct l.userlogid) as num_log_users, count(distinct case when o.status = 1 then l.userlogid end) as num_status1_users from allusers u left join userlog l on l.userlogid = u.USERID group by o.department;

distinct