Repeat total count value
-
02-10-2020 - |
Question
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.
Solution
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 ;