1. 程式人生 > >hive學習之經典sql50題 hive版(二)

hive學習之經典sql50題 hive版(二)

1.查詢“某1”課程比“某2”課程成績高的所有學生的學號
select s.id
from
(
select s1.sid id,s1.score c1,s2.score c2
from (
select sid,score from sc where cid=1
) s1
join (
select sid,score from sc where cid=2
) s2 
on s1.sid=s2.sid
) s

where s.c1>s.c2;

2.查詢平均成績大於60分的同學的學號和平均成績;

select sid,round(avg(score),1) from sc group by sid having avg(score)>60;

3.查詢所有同學的學號、姓名、選課數、總成績
select student.sid,student.sname,s.num,s.total
from
(
select sid id,count(cid) num,sum(score) total 
from sc group by sid
) s
join student
on s.id=student.sid;

4.查詢姓“李”的老師的個數

select count(tname) from teacher where tname like '李%';

5.查詢沒學過“張三”老師課的同學的學號、姓名
select notstudy.sid,student.sname
from
(
select all.sid sid
from
(
select distinct sid from sc 
) all
left join
(
select sid sid
from
(
select course.cid c
from
(
select tid from teacher where tname='張三'
) t
join course
on t.tid=course.tid
) c
join sc
on sc.cid=c.c
) s
on s.sid=all.sid
where s.sid is null
) notstudy
join student

on student.sid=notstudy.sid;

6.查詢學過數學並且也學過編號語文課程的同學的學號、姓名
select ch.s
from
(
select sc.sid s
from
(
select cid from course where cname='語文'
) c
join sc
on c.cid=sc.cid
) ch
join
(
select sc.sid s
from
(
select cid from course where cname='數學'
) c
join sc
on c.cid=sc.cid
) ma

on ch.s=ma.s;

7.查詢學過“張三”老師所教的所有課的同學的學號、姓名
select s.s sid,student.sname sname
from
(
select sid s
from
(
select course.cid c
from
(
select tid from teacher where tname='張三'
) t
join course
on t.tid=course.tid
) c
join sc
on sc.cid=c.c
) s
join student
on s.s=student.sid


8.查詢課程編號“01”的成績比課程編號“02”課程低的所有同學的學號、姓名
select s.id
from
(
select s1.sid id,s1.score c1,s2.score c2
from (
select sid,score from sc where cid=1
) s1
join (
select sid,score from sc where cid=2
) s2 
on s1.sid=s2.sid
) s

where s.c1<s.c2;

9.查詢所有課程成績小於60分的同學的學號、姓名
select stu.sid,student.sname
from
(
select lt60.sid sid
from
(
select s.sid sid,count(s.sid) c
from
(
select sid from sc 
where score<=60
) s
group by s.sid
) lt60
join
(
select sid sid,count(1) c
from sc 
group by sid
) all
on lt60.sid=all.sid and lt60.c=all.c
) stu
join student
on stu.sid=student.sid;

10.查詢沒有學全所有課的同學的學號、姓名

select s.sid,student.sname
from
(
select sid from sc group by sid having count(1)<3
) s
join student
on s.sid=student.sid;