題目一:
有一個【保單車輛】數據庫,數據庫包括三個表:
1、保單表:保單號(po)、被保險人(iname)、產品類型(pc)、保險起期(sdate)、保險止期(edate),
五個屬性組成,記為:t_poliey_base(po,iname,pc,sdate,edate), po 為關鍵字。
2、車輛表:車輛編號(vo)、車牌號碼(vc)、品牌(vbrand)、 車架號(vframe)、制造日期(vdate)
五個屬性組成,記為:t_vehicele(vo,vc,vbrand,vframe,vdate),vo為關鍵字。
3、保單車輛表:保單號(po), 車輛編號(vo)、創建時間(cdate)
三個屬性組成,記為:t_poliey_vehicle(po,vo,cdate)
# 1.將一個保單記錄( 保單號:010,被保人:小美,產品類型: 109, 保險起期:2021-01 -01,保險止期:2021-12-31 )
insert into t_policy_base values('010','小美',109,'2021-01-01', '2021-12-31');
# 2.刪除車輛表中車輛編號為 001 的數據;
delete from t_vehicle where po = '001';
# 3.將保單號為 002 的被保險人改為 “李四”;
update t_policy_base set iname='李四' where po = 002;
# 4.查詢保單表中起保時商大於 2021-02-01 的所有數據,按照保單號降序排列;
select * from t_policy_base where sdate > '2021-02-01' order by po desc ;
# 5.查詢品牌為寶馬並且產品類型為109的所有車牌號碼,車架號,保單號,被保險人;
select b.vc, b.vframe, a.po, a.iname from t_policy_base a ,t_vehicele b,t_poliey_vehicle c where a.po = c.po and b.vo = c.vo and b.vbrand = '寶馬’ and a.pc = 109;
題目二:
查詢每門課程都大於80分的學生姓名
1、最小分數 > 80
select C.name from C group by c.name HAVING min (C.fenshu) > 80;
2、子查詢,排除小於80的,只要有一門沒超過 80分 就不符合要求
select DISTINCT C.name from C where C.name not in (select C.name from C where C.fenshu <= 80);
題目三:集團有多個部門,部門下有多名員工,求每個部門績效分數排名第二的人員
根據部門自連接,再給每個員工績效排序
第一種:先再組內進行排序,並添加一列,再取第二名的人員;
select *, (select count(*) from b b1 where b1.departmentid = b2.departmentid and b1.score <= b2.score ) from b b2;
select * from b b2 where (select count(*) from b b1 where b1.departmentid = b2.departmentid and b1.score >= b2.score ) = 2;
第二種:先排除最大的,再用 not in 取當前最大的就是第二名
select max(b.score),b.name from b where b.score not in ( select max(b.score) from b group by b.departmentid ) group by b.departmentid ;
第二行SQL取出最大的結果為:
第一二行SQL結果為:
全部執行結果為:
題目四:
1、查詢數學平均成績最好的那個班級
->兩表關聯,所有數學成績
->分組平均值
->排序取第
第一步:先查每個班級的平均成績
select avg(a.score) from scores a, student b where a.name = b.name and a.course = '數學' group by b.class;
# avg(a.score):平均成績;b.class:班級;scores a, student b查詢那兩個表 select avg(a.score) as avgscore, b.class from scores a, student b # 兩個表之間的關聯條件;及數學平均成績 where a.name = b.name and a.course = '數學' # group by=根據班級分組;order by=平均成績排序;limit=取第一個 group by b.class order by avgscore desc limit 1;