按标识

时间:2016-02-12 02:55:26

标签: sql sqlite join

我的数据库中有一个表格,其格式如下

author | status
---------------
Michael | New
Michael | New
Kevin | Repost
Kevin | New
Michael | Repost
Steve | New

我如何构建一个计算新状态和重新发布状态的查询,并将它们放在作者姓名旁边

即。将输出以下查询

author | # new | # repost
-------------------------
Michael | 2 | 1
Kevin | 1 | 1
Steve | 1 | 0

我遇到的问题是,如果有一种类型的帖子的X而另一种类型的0,则忽略整行。

这是我到目前为止的查询:

SELECT New.post_author, Newc, Repostc from (
SELECT post_author, count(*) as 'Newc' FROM flair WHERE status = 'New' GROUP BY post_author) as New
inner join (
SELECT post_author, count(*) as 'Repostc' FROM flair WHERE status='Repost' GROUP BY post_author) as Repost 
on New.post_author = Repost.post_author

除了输出以下查询外:

author | # new | # repost
-------------------------
Michael | 2 | 1
Kevin | 1 | 1

完全无视史蒂夫

1 个答案:

答案 0 :(得分:2)

只需使用条件聚合:

select post_author,
       sum(case when status = 'New' then 1 else 0 end) as newposts,
       sum(case when status = 'Repost' then 1 else 0 end) as reposts
from flair f
group by post_author;