【问题标题】:SQLite Group Multiple Sub Queries by IDSQLite 按 ID 分组多个子查询
【发布时间】:2016-02-12 02:55:26
【问题描述】:

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

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

完全无视史蒂夫

【问题讨论】:

    标签: sql sqlite join


    【解决方案1】:

    只使用条件聚合:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      相关资源
      最近更新 更多