问题:
答案:
新手答案
-- 条件一
-- -- 使用having子句过滤分组后的数据
select std_id, max(club_id) as main_club
from student_club
group by std_id
having count(*) = 1;
-- 条件二
select sdt_id, club_id as main_club
from student_club
where main_club_flg = 'Y';
高手答案
-- 高手答案
select std_id,
case when count(*) = 1
then max(club_id)
else max(case when main_club_flg = 'Y'
then club_id
else null
end)
end as main_club
from student_club
group by std_id;
/ 在CASE表达式中使用聚合函数, 在聚合函数中使用CASE表达式 /