34,827
社区成员
如何分两层聚合,再行转列
;with t1 as
(
select id = '00' ,班组id = 'A1',人员id = 'A',证书 = 'A'union all
select id = '00' ,班组id = 'A1',人员id = '班长',证书 = '班长证'union all
select id = '00' ,班组id = 'A1',人员id = 'C',证书 = 'A'union all
select id = '00' ,班组id = 'A2',人员id = 'A',证书 = 'A'union all
select id = '00' ,班组id = 'A3',人员id = '班长',证书 = '班长证书'union all
select id = '00' ,班组id = 'A4',人员id = '副班长',证书 = '证书'union all
select id = '00' ,班组id = 'A5',人员id = 'A',证书 = 'A'
)
目标:
id 班组数量 班组名 有班长 班长有证书
00 5 A1 yes yes
00 5 A2
00 5 A3 yes yes
00 5 A4
00 5 A5
用一个窗口函数做统计即可
with t1 as
(
select id = '00' ,班组id = 'A1',人员id = 'A',证书 = 'A'union all
select id = '00' ,班组id = 'A1',人员id = '班长',证书 = '班长证'union all
select id = '00' ,班组id = 'A1',人员id = 'C',证书 = 'A'union all
select id = '00' ,班组id = 'A2',人员id = 'A',证书 = 'A'union all
select id = '00' ,班组id = 'A3',人员id = '班长',证书 = '班长证书'union all
select id = '00' ,班组id = 'A4',人员id = '副班长',证书 = '证书'union all
select id = '00' ,班组id = 'A5',人员id = 'A',证书 = 'A'
)
select id, sum(count(distinct 班组id)) over(partition by id) 班组数量, 班组id,
case when sum(count(case when 人员id = '班长' then 1 else null end)) over(partition by id, 班组id) > 0
then 'yes'
else null end 有班长,
case when sum(count(case when 人员id = '班长' and 证书 like '班长证%' then 1 else null end)) over(partition by id, 班组id) > 0
then 'yes'
else null end 班长有证书
from t1
group by id, 班组id
我又来了