PostgreSQL:合并 Count 和 DISTINCT ON

标签 postgresql count distinct

给定这张表

| id | name  | created_at                 |
| 1  | test  | 2015-02-24 11:13:28.605968 |
| 2  | other | 2015-02-24 13:04:56.968004 |
| 3  | test  | 2015-02-24 11:14:24.670765 |
| 4  | test  | 2015-02-24 11:15:05.293904 |

这个查询只返回行 id 2 和 id 4。

SELECT DISTINCT ON (documents.name) documents.*
FROM "documents"  
ORDER BY documents.name, documents.created_at DESC

如何返回受影响的行数?有点像

SELECT COUNT(DISTINCT ON (documents.name) documents.*) FROM "documents"

最佳答案

您可以使用外部查询:

SELECT COUNT(1)
FROM (
    SELECT DISTINCT ON (name) *
    FROM documents
    ORDER BY name, created_at DESC
    ) alias

关于PostgreSQL:合并 Count 和 DISTINCT ON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30981029/

相关文章:

java - 我在 JSP 中的 SQL 查询在服务器环境中不起作用

postgresql - 服务器版本不匹配 postgresql pg_dump

r - 计算相同行的数量

mysql - 如何选择两个表的不同值?

python - Postgres 错误 “ERROR: INSERT has more target columns than expressions”

postgresql - mix deps.get 失败(依赖问题)

excel - 根据某一列中重复值的计数对数据进行分组

Python PySpark : Count Number of Rows by Week w/Week Starting on Monday and Ending on Sunday

c# - 防止 RegEx 中的重复匹配

mysql - 如何在 MYSQL 中使用 COUNT 和 DISTINCT 为每个不同值创建单独的计数?