原表
groupid id type
1 1 1
1 2 2
1 3 2
1 4 3
1 5 4
1 6 4
1 7 5
2 ...`要求
同组中当且仅当存在1 输出grouptype 1
同组中即存在1又存在其他数 输出grouptype 2
同组中当且仅当存在3 输出grouptype 3
同组中即存在3又存在其他数(没有1) 输出grouptype 4结果
groupid grouptype
1 1
2 2
3 3
4 1
5...
groupid id type
1 1 1
1 2 2
1 3 2
1 4 3
1 5 4
1 6 4
1 7 5
2 ...`要求
同组中当且仅当存在1 输出grouptype 1
同组中即存在1又存在其他数 输出grouptype 2
同组中当且仅当存在3 输出grouptype 3
同组中即存在3又存在其他数(没有1) 输出grouptype 4结果
groupid grouptype
1 1
2 2
3 3
4 1
5...
,case when type1>0 and count>type1 then 2 else 0 end type2
,case when type3=count then 3 else 0 end type3
,case when type3>0 and count>type3 and type1=0 then 4 else 0 end type2
from
(
select groupid,sum(case when type=1 then 1 else 0 end) type1
,sum(case when type=3 then 1 else 0 end) type2
,count(*) count
from tb
group by groupid
)
实现!! case when 语句!