Chris L
Chris L

Reputation: 35

Group By and add columns

I have a table named 'ward_councillors' and two columns 'ward' and 'councillor'. This table contains a list of all of the councillors and the ward they are responsible for. Each ward has three councillors and what i'd need to do is group by so that I have one distinct record for each ward and three new columns with the three councillors responsible for that ward in each.

For example currently have:

WARD   | COUNCILLOR
ward a | cllr 1
ward a | cllr 2
ward a | cllr 23
ward b | cllr 4
ward b | cllr 5
ward b | cllr 8

trying to achieve:

WARD    | COUNCILLOR 1| COUNCILLOR 2| COUNCILLOR 3
ward a  | cllr 1      | cllr 2      | cllr 23
ward b  | cllr 4      | cllr 5      | cllr 8

Thanks in advance, Chris

Upvotes: 2

Views: 118

Answers (2)

murison
murison

Reputation: 3983

I have a problem with sqlFiddle, but I wrote this on my local postgres:

CREATE TABLE ward_councillors (
  ward VARCHAR
  , councillor VARCHAR
);

INSERT INTO ward_councillors
VALUES 
('ward a', 'cllr 1')
, ('ward a', 'cllr 2')
, ('ward a', 'cllr 23')
, ('ward b', 'cllr 4')
, ('ward b', 'cllr 5')
, ('ward b', 'cllr 8')
;


SELECT * 
FROM crosstab('SELECT ward, null /*doesnt really matter*/, councillor  FROM  ward_councillors') 
    AS (ward VARCHAR, councillor_1 VARCHAR, councillor_2 VARCHAR, councillor_3 VARCHAR, councillor_4 VARCHAR)
;

Seems to output just what you wanted:

  ward  | councillor_1 | councillor_2 | councillor_3 | councillor_4
--------+--------------+--------------+--------------+--------------
 ward a | cllr 1       | cllr 2       | cllr 23      |
 ward b | cllr 4       | cllr 5       | cllr 8       |
(2 rows) 

It is all described here: http://www.postgresql.org/docs/9.1/static/tablefunc.html#AEN142967

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269503

I tend to approach this type of query using conditional aggregation:

select ward,
       max(case when seqnum = 1 then councillor end) as councillor1,
       max(case when seqnum = 2 then councillor end) as councillor2,
       max(case when seqnum = 3 then councillor end) as councillor3
from (select wc.*,
             row_number() over (partition by ward order by councillor) as seqnum
      from ward_councillors wc
     ) wc
group by ward;

Upvotes: 4

Related Questions