PostgreSQL:合并 Count 和 DISTINCT ON
PostgreSQL: Combine Count and DISTINCT ON
鉴于此 table
| 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 |
而此查询 return 只有行 ID 2 和 ID 4。
SELECT DISTINCT ON (documents.name) documents.*
FROM "documents"
ORDER BY documents.name, documents.created_at DESC
如何 return 影响行数?像
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
鉴于此 table
| 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 |
而此查询 return 只有行 ID 2 和 ID 4。
SELECT DISTINCT ON (documents.name) documents.*
FROM "documents"
ORDER BY documents.name, documents.created_at DESC
如何 return 影响行数?像
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