So I have a column where I do a string\_agg in a table as follows

```
select buildingid, string_agg(distinct cast(obligatioNr as varchar(2)), ', ') as SPJ
...

```

the values of this field has values between 0-12

[![enter image description here](https://i.stack.imgur.com/fSx0C.png)](https://i.stack.imgur.com/fSx0C.png)

I want the total values of each number and all this stored in the final line in 1 column.

[![enter image description here](https://i.stack.imgur.com/hSAg6.png)](https://i.stack.imgur.com/hSAg6.png)

My code is along the lines of 

```
with results as 
(
    select  id, amount, SPJ
    FROM 
    (
        SELECT building.id as ids,
            count(distinct s.studentnr) as amount,
            string_agg(distinct cast(so.obligationnr as varchar(2)), ', ') as SPJ,

        from ....

        GROUP BY building.id
    ) t

    GROUP BY ids, amount,SPJ

    ORDER BY ids
)
    SELECT *
    FROM results 
    UNION all
    SELECT NULL as ids,
    SUM(amount),
    null as SPJ
    FROM results 

```

I am using Postgres 9.3