我有两个问题:
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
最佳答案
你可以使用 FILTER
子句:
The filter clause extends aggregate functions (sum, avg, count, …) by an additional where clause. The result of the aggregate is built from only the rows that satisfy the additional where clause too.
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
关于postgresql - 合并两个分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52764477/