建表语句
create table student_score
(
name string
,object string
,score float
) comment '学生成绩表'
;
数据展示
| name | object | score |
|---|---|---|
| 张三 | 语文 | 60 |
| 张三 | 数学 | 70 |
| 李四 | 语文 | 80 |
| 李四 | 数学 | 90 |
行转列效果
| name | chinese | math |
|---|---|---|
| 张三 | 60 | 70 |
| 李四 | 80 | 90 |
分析:记录行数变少了,一般是使用了group by进行了聚合操作
代码实操:
select name ,sum(if(object='语文',score,0)) as chinese --根据场景一般可以选择sum、max ,sum(if(object='数学',score,0)) as math from student_score group by name列转行
建表语句
create table student_score
(
name string
,chinese float
,math float
) comment '学生成绩表'
;
数据展示
| name | chinese | math |
|---|---|---|
| 张三 | 60 | 70 |
| 李四 | 80 | 90 |
列转行效果
| name | object | score |
|---|---|---|
| 张三 | 语文 | 60 |
| 张三 | 数学 | 70 |
| 李四 | 语文 | 80 |
| 李四 | 数学 | 90 |
分析:记录行数变多了,一般是使用了union on
代码实操:
select name ,'语文' ,chinese from student_score union all select name ,'数学' ,math from student_score
点赞收藏吧~



