、
關(guān)聯(lián)找出前三名,返回名字和分?jǐn)?shù)的合并值,注意可能有并列存在。表格中學(xué)生各科成績在一列,所有課程名稱在一列,學(xué)生名稱在一列,當(dāng)然在三個(gè)表中。
返回結(jié)果其實(shí)也用到了列轉(zhuǎn)行,但是此題需求更為明顯。因?yàn)槭橇修D(zhuǎn)行,用不到limit;
我的代碼:
select t.lesson_id,
group_concat(if(排序=1,stu_name,null),score) 第一名,
group_concat(if(排序=2,stu_name,null),score) 第二名,
group_concat(if(排序=3,stu_name,null),score) 第三名
from
(select ts.stu_id, ts.lesson_id, score, stu_name, lesson_name,
dense_rank() over(partition by ts.lesson_id order by score) 排序
from t_score ts
left join t_stu_profile tsp
on ts.stu_id=tsp.stu_id
left join t_lesson tl
on ts.lesson_id=tl.lesson_id) t
group by t.lesson_id;
老師的:
select
lesson_name,
group_concat(if(排名=1,concat(stu_name,'+',score),null)) as 第一名,
group_concat(if(排名=2,concat(stu_name,'+',score),null)) as 第二名,
group_concat(if(排名=3,concat(stu_name,'+',score),null)) as 第三名
from
(select
lesson_name,
score,
stu_name,
dense_rank() over(partition by t_score.lesson_id order by score desc) as 排名
from t_score
left join t_lesson
on t_lesson.lesson_id=t_score.lesson_id
left join t_stu_profile
on t_stu_profile.stu_id=t_score.stu_id) as t
group by lesson_name;
注意:自己的比老師精簡了一個(gè)concat,都用到group_concat()








暫無數(shù)據(jù)