本文介绍了分组依据并添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为"ward_councillors"的表以及两列"ward"和"councillor".该表包含所有议员和他们所负责的病房的列表.每个病房都有三名议员,而我需要做的是分组,以便我为每个病房拥有一个不同的记录,并在三个新的栏目中各负责该病房的三名议员.
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.
例如当前具有:
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
预先感谢,克里斯
推荐答案
我倾向于使用条件聚合来处理这种类型的查询:
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;
这篇关于分组依据并添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!