Пример данных:
create table mytable(location text, class text);
insert into mytable values
('Wakanda', 'warrior'),
('Wakanda', 'warrior'),
('Wakanda', 'priest'),
('Wakanda', 'tank'),
('Wakanda', 'tank'),
('Wakanda', 'warrior');
Использование группировки наборов. Вы можете легко получить хороший табличный вывод:
select location, class, count(*)
from mytable
group by grouping sets ((location), (location, class));
location | class | count
----------+---------+-------
Wakanda | priest | 1
Wakanda | tank | 2
Wakanda | warrior | 3
Wakanda | | 6
(4 rows)
или одну строку для местоположенияНапример:
select
max(count) as units,
location,
string_agg(class || ': ' || count, ', ') as counts
from (
select location, class, count(*)
from mytable
group by grouping sets ((location), (location, class))
) s
group by location;
units | location | counts
-------+----------+--------------------------------
6 | Wakanda | priest: 1, tank: 2, warrior: 3
(1 row)