结合两个小组?

时间:2018-10-11 16:06:14

标签: postgresql

我有两个查询:

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 个答案:

答案 0 :(得分:4)

您可以使用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

答案 1 :(得分:2)

您可以在一个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;

答案 2 :(得分:1)

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;