相关疑难解决方法(0)

PostgreSQL中的GROUP BY和COUNT

查询:

SELECT COUNT(*) as count_all, 
       posts.id as post_id 
FROM posts 
  INNER JOIN votes ON votes.post_id = posts.id 
GROUP BY posts.id;
Run Code Online (Sandbox Code Playgroud)

返回nPostgresql 中的记录:

 count_all | post_id
-----------+---------
 1         | 6
 3         | 4
 3         | 5
 3         | 1
 1         | 9
 1         | 10
(6 rows)
Run Code Online (Sandbox Code Playgroud)

我只想检索返回的记录数:6.

我使用子查询来实现我想要的,但这似乎不是最佳的:

SELECT COUNT(*) FROM (
    SELECT COUNT(*) as count_all, posts.id as post_id 
    FROM posts 
    INNER JOIN votes ON votes.post_id = posts.id 
    GROUP BY posts.id
) as x;
Run Code Online (Sandbox Code Playgroud)

如何在PostgreSQL中获得此上下文中的记录数?

sql postgresql count distinct aggregate-functions

34
推荐指数
3
解决办法
9万
查看次数

标签 统计

aggregate-functions ×1

count ×1

distinct ×1

postgresql ×1

sql ×1