某一位同事在工作中遇到一个场景,需要将group by分组的子类内容以列的形式展示,列字段用于后续作为子表进行left join关联计算。应该如何实现呢?具体详见以下案例:

案例场景

找出以下表格中每位同学成绩最好的科目,将科目名称展示出来

id name subject score
1 数学 100
2 语文 98
3 英语 120
4 数学 110
5 英语 100
6 语文 97

假设group by 之后的结果为上述结果: select * from row_to_column 要达到查询效果为如下结构: | 姓名 | 数学 | 语文 | 英语 | |----|----|----|----| | 赵| 100| 98 | 120 | | 钱 | 110| 97 | 100 |

答案

SELECT name as "姓名",

max(case subject when "数学" then score end ) as "数学",

max(case subject when "语文" then score end ) as "语文",

max(case subject when "英语" then score end ) as "英语"

from row_to_column GROUP BY name

解析

如果SQL直接写成如下,则会出现很多null select name as "姓名",

case when subject="数学" then score end as "数学",

case when subject="数学" then score end as "数学",

case when subject="数学" then score end as "数学",

from row_to_column 故进而可以根据姓名分组取每科最大的值,刚好每科最大的就是其真实分数。

版权声明:本站部分文章为原创,部分内容来自网络转载,如有任何问题,可联系本站本站管理员邮箱!

本文链接:http://www.btdiv.com/article/row_to_column/