Skip to content
Advertisement

Postgres: column “all_comments.id” must appear in the GROUP BY clause or be used in an aggregate function

I am using with recursive to count the number of all descendants. That would be the following SQL query, but if I specify only root_id for group by, I get I get the following error.

column "all_comments.id" must appear in the GROUP BY clause or be used in an aggregate function

I don’t understand why this error occurs with all_comments.id. Also, if I add all_comments.id to group by, this error does not occur, but The original purpose of the all_descendants.id does not count well, and rows of all descendants are returned.

I do not want to remove this column from the SELECT because we need to retrieve the id and other columns as well.

What can I do to resolve this? Your help would be greatly appreciated.

Sample data and desired output

— Edit — Using the window function

Results obtained

We need to get only those with parent_id null, but if we add WHERE parent_id is null, all_descendants_count will be 0.

Advertisement

Answer

Add a filter step after counting over the entire dataset, for example

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement