我有一张名为' ward_councillors'和两列' ward'和'议员'。该表包含所有议员及其负责的病房的清单。每个病房有三名议员,我需要做的就是分组,这样我每个病房都有一个不同的记录和三个新的栏目,三个议员分别负责该病房。
例如目前有:
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
试图实现:
WARD | COUNCILLOR 1| COUNCILLOR 2| COUNCILLOR 3
ward a | cllr 1 | cllr 2 | cllr 23
ward b | cllr 4 | cllr 5 | cllr 8
提前致谢, 克里斯
答案 0 :(得分:4)
我倾向于使用条件聚合来处理这种类型的查询:
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;
答案 1 :(得分:1)
我的sqlFiddle存在问题,但是我在本地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)
;
似乎输出你想要的东西:
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)
这里全部描述:http://www.postgresql.org/docs/9.1/static/tablefunc.html#AEN142967