Q1

​ 在学生选修表 SC 与课程表 C 放置一些数据,写一条 SQL 求出选修了 C 表所列全部课程 的学生名单

​ 思想:选出学生选课数等于总课程数

1
2
3
4
5
6
7
select * from s 
where S# in(
select S# from sc group by S#
having count(*) = ( /*该学生的选修的课程门数 = 所有课程的门数*/
select count(*) from c
)
);

image-20220405095826280

Q2

在 SC 表中加入大量数据,然后用 pivot 函数将它转为宽表 SCwide。再用 unpivot 函数将 SCwide 转为窄表

1
2
3
4
5
6
7
create table SCwide as
select * from sc
pivot
(
sum(g)
for C# in ('C1' C1,'C2' C2,'C3' C3,'C4' C4,'C5' C5)
);

image-20220405102233005

1
2
3
4
5
select * from scwide
unpivot
(
g for C# in (C1,C2,C3,C4,C5)
)

image-20220405102252174

Q3

用 1 条 SQL 语句建立以下统计表格,分别统计每个部门,每个年份进入公司,每个工种的人数

1
select deptno,to_number(to_char(hiredate,'yyyy')) year,job,count(empno) num from emp group by rollup(deptno,to_number(to_char(hiredate,'yyyy')),job);

image-20220405104512952

Q4

​ 有 A,B 两张表,均有 C1,C2 两列,C1 代表商品名称,C2 代表商品价格。B 中的商品有 些是 A 中的原有商品,有些是在 A 中没有的新商品,要求对 A 表进行更新修改,B 中原有 商品用 B 里的新价格覆盖 A 的原价格,B 中的新商品则插入到 A 中,要求 1 条 SQL 语句完成

1
2
3
4
5
6
7
8
merge into A  
using B
on(A.C1=B.C1)
when matched then
update set A.C2 = B.C2
WHEN NOT MATCHED THEN
INSERT(A.C1,A.C2) VALUES (B.C1,B.C2)
;

image-20220405105603280

image-20220405105610390

image-20220405105632896