postgresql - 合并两个分组?

标签 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

最佳答案

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

相关文章:

PostgreSQL 到数据仓库 : Best approach for near-real-time ETL/extraction of data

sql - 使用 LIKE/ILIKE 加入 PostgreSQL

PostgreSQL 9.5 : Hide password from dblink connection

PostgreSQL 插入或更新触发函数波动类别

PostgreSQL 本地时间

sql - 按各种属性比较两个大表 - PostgreSQL

mysql - SQL:INSERT + SET - 标准的还是特定于 MySQL 的?

python - 如何仅从时间戳列中检索年份?

sql - 如何在 AMAZON REDSHIFT 中将 userip 转换为整数

python - 如何使用 Python 的 DBAPI 来可移植地验证数据库模式?