Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY and COUNT in PostgreSQL

The query:

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; 

Returns n records in Postgresql:

 count_all | post_id -----------+---------  1         | 6  3         | 4  3         | 5  3         | 1  1         | 9  1         | 10 (6 rows) 

I just want to retrieve the number of records returned: 6.

I used a subquery to achieve what I want, but this doesn't seem optimum:

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; 

How would I get the number of records in this context right in PostgreSQL?

like image 942
skinkelynet Avatar asked Aug 04 '12 09:08

skinkelynet


People also ask

Can count be used with GROUP BY?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

What is GROUP BY in PostgreSQL?

The PostgreSQL GROUP BY clause is used in collaboration with the SELECT statement to group together those rows in a table that have identical data. This is done to eliminate redundancy in the output and/or compute aggregates that apply to these groups.

How do I count values in PostgreSQL?

You can use the COUNT(Column_name) function along with a SELECT statement to return the total number of non-NULL values in the Column_name column.

Can we use GROUP BY without count?

Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.


1 Answers

I think you just need COUNT(DISTINCT post_id) FROM votes.

See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.

EDIT: Corrected my careless mistake per Erwin's comment.

like image 156
Steve Jorgensen Avatar answered Sep 19 '22 12:09

Steve Jorgensen