我有一张名为“沃德议员”的桌子和两列“沃德”和“议员”。这张表列有所有议员及其负责的病房的名单。每个病房有三名议员,我需要做的是分组,以便我有一个不同的记录,每个病房和三个新的专栏,三名议员负责每个病房。
例如,目前有:
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
提前谢谢你,
克里斯
最佳答案
我倾向于使用条件聚合来处理此类查询:
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;
关于sql - 分组依据并添加列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28853708/