背景
数仓很火的情况下,sql是bi'xu必须要会的,这也是面试了好几家大厂都碰壁的问题,所以写个专题练练sql。
一、建表
//1、学生信息表
hive> create table xcj_student (s_id string,s_name string,s_birth string,s_sex string) row format delimited fields terminated by '\t';
OK
Time taken: 1.176 seconds
//2、课程表
hive> create table xcj_course(c_id string , c_name string, t_id string ) row format delimited fields terminated by '\t';
OK
Time taken: 0.211 seconds
//3、老师表
hive> create table xcj_teacher (t_id string, t_name string) row format delimited fields terminated by '\t';
OK
Time taken: 0.113 seconds
//4、成绩表
hive> create table xcj_score(s_id string ,c_id string ,s_core int ) row format delimited fields terminated by '\t';
OK
Time taken: 0.064 seconds
二、生成数据
1、vi /student.txt
学生编号|姓名|出生年月|性别
01 赵雷 1990-01-01 男
02 钱电 1990-12-21 男
03 孙风 1990-05-20 男
04 李云 1990-08-06 男
05 周梅 1991-12-01 女
06 吴兰 1992-03-01 女
07 郑竹 1989-07-01 女
08 王菊 1990-01-20 女
2、vi /course.txt
编号|课程名称|课程编号
01 语文 02
02 数学 01
03 英语 03
3、vi /teacher.txt
编号|教师姓名
01 张三
02 李四
03 王五
4、vi /score.txt
学生编号|课程编号|成绩
01 01 80
01 02 90
01 03 99
02 01 70
02 02 60
02 03 80
03 01 80
03 02 80
03 03 80
04 01 50
04 02 30
04 03 20
05 01 76
05 02 87
06 01 31
06 03 34
07 02 89
07 03 98
三、导数据到hive
load data local inpath '/data/xuecj02/data/student.txt' into table xcj_student;
load data local inpath '/data/xuecj02/data/teacher.txt' into table xcj_teacher;
load data local inpath '/data/xuecj02/data/course.txt' into table xcj_course;
load data local inpath '/data/xuecj02/data/score.txt' into table xcj_score;
四、hive查询语法
select
from table
where
group by having
cluster by distribute by sort by order by
limit
五、例子
1、查询『01』课程比『02』课程成绩高的学生的信息以及课程分数
select * from xcj_student s
join xcj_score a on s.s_id =a.s_id and a.c_id='01'
left join score b on s.s_id=b.s_id and b.c_id='02'
where a.s_score > b.score;