代码之家  ›  专栏  ›  技术社区  ›  Theodore R. Smith

合并两组BY?

  •  1
  • Theodore R. Smith  · 技术社区  · 7 年前

    我有两个问题:

    SELECT to_char(pubdate, 'YYYY-MM') pub_month, COUNT(*) total 
    FROM books 
    GROUP BY pub_month;
    

    SELECT to_char(pubdate, 'YYYY-MM') pub_month, COUNT(*) total_bought 
    FROM books 
    WHERE purchased=true 
    GROUP BY pub_month;
    

    +-----------+-------+--------------
    | pub_month | total | total_bought 
    +-----------+-------+--------------
    |   2018-10 |     5 |            2
    |   2018-09 |    10 |            7
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Lukasz Szozda    7 年前

    你可以用 FILTER 条款:

    filter子句通过额外的where子句扩展聚合函数(sum、avg、count等)。 聚合的结果也仅从满足附加where子句的行生成。

    SELECT to_char(pubdate, 'YYYY-MM') pub_month
        , COUNT(*) FILTER (WHERE purchased) total_bought
        , COUNT(*) total 
    FROM books 
    GROUP BY pub_month;
    

    SELECT to_char(pubdate, 'YYYY-MM') pub_month
        , SUM(CASE WHEN purchased THEN 1 ELSE 0 END) total_bought
        , COUNT(*) total 
    FROM books 
    GROUP BY pub_month;
    

    附加说明: WHERE purchased=true WHERE purchased

        2
  •  2
  •   Grzegorz Grabek    7 年前

    您可以在一个sql查询中创建它。

    SELECT to_char(pubdate, 'YYYY-MM') pub_month, COUNT(*) total , 
           sum(case when purchased=true then 1 else 0 end) total_bought 
    FROM books 
    GROUP BY pub_month;
    
        3
  •  1
  •   Cade Roux    7 年前
    SELECT to_char(pubdate, 'YYYY-MM') pub_month
               , COUNT(*) total
               , SUM(CASE WHEN purchased=true THEN 1 ELSE 0 END) total_bought 
    FROM books 
    GROUP BY pub_month;