1

I have a table called paths that looks like this:

id  parent_id
--  ---------
 1       null
 2          1
 3          2
 4          3
 5          4
 6          5
 7          5
 8          5
 9          5
10          5
11          1
12         11
13         12
14          1
15          2
16         15
17          3
18          2
19         18
20         19

I have the query:

SELECT count (id) as count_id, id FROM paths where parent_id=5 group by id

It returns me:

count_id  id
--------  --
1          6
1          8
1          9
1          7
1         10

But I want to get the following:

total_count  id  parent_id
-----------  --  ---------
5             6          5
5             8          5
5             9          5
5             7          5
5            10          5

Since the total count is 5, I want to show 5 in every column. What I am doing is finding all nodes whose parent id is the specified number, count the nodes and return every found node along with that total number.

If I found nothing, I'd like to have

total_count  id    parent_id
-----------  ----  ---------
0            null       null

Is there a way to do it? I use PostgreSQL 9.5.

1 Answer 1

4

The GROUP BY id is useless in the query, since there is only one row for every id (it appears to be the primary key of the table).

What you need a count over the whole result. This is easy using a window aggregate:

SELECT count(*) OVER () AS total_count, 
       id, parent_id
FROM paths 
WHERE parent_id = 5 ; 

The last requirement is rather weird but you could have that, too, with a more complicated construct:

SELECT count(p.id) OVER () AS total_count, 
       p.id, p.parent_id
FROM (SELECT 1) AS dummy
  LEFT JOIN paths AS p
    ON p.parent_id = 5 ; 
2
  • I would use this solution, even though it doesn't cover the last requirement.
    – Andriy M
    Commented Jun 2, 2016 at 14:24
  • it is weird because I want to differ the case when the id doesn't exist at all in the table paths from the case when the id doesn't have any children. I think I have a bad explanantion
    – user565447
    Commented Jun 2, 2016 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.