需要帮助在Microsoft SQL Server中分组和创建选择语句

时间:2018-10-09 19:37:05

标签: sql sql-server

我有3个具有以下结构的表:

enter image description here

我正在寻找的结果是:

enter image description here

我尝试了多种分组语句,但是如果有人可以帮我忙,我就无法接近所需的结构。谢谢

1 个答案:

答案 0 :(得分:3)

这是一种方法:

select u.userid, u.name,
       count(distinct case when b.visibility = 1 then b.blogid end) as num_public_blogs,
       count(distinct case when b.visibility = 0 then b.blogid end) as num_private_blogs,
       count(case when b.visibility = 1 then bp.blogid end) as num_public_posts,
       count(case when b.visibility = 0 then bp.blogid end) as num_private_posts
from users u left join
     blogs b
     on b.userid = u.userid left join
     blogposts bp
     on bp.blogid = b.blogid
group by u.userid, u.name;
相关问题