1. 程式人生 > 其它 >SQL 資料庫———高階子查詢

SQL 資料庫———高階子查詢

------------恢復內容開始------------

------------恢復內容開始------------

1.掌握簡單的子查詢的用法

1.查詢tb_stu中比你輸入的那個人的名字大的年齡的學生資訊

select*from tb_stu where sage>(

select sage from tb_stu where sname='名字'

2.比班級平均分高的學生資訊

select *from tb_grade where grade>(

select avg(grade) from tb_grade

)


-- 學生表的男性的總人數
select count(*) as '男性人數' from stuInfo
where stuSex='男';

-- 男女的人數
select stuSex,count(*) from stuInfo group by stuSex;

-- 表關聯操作
select * from stuInfo a inner join stuMarks b
on a.stuNo=b.stuNo;

-----------------------------------------------------
-- 將一個sql語句的結果作為條件來判斷:子查詢
-- 子查詢的語句,查詢的列只允許一個
-- 子查詢的語句,如果使用=,>,<,<=,>=結果必須只有一行
-- 如果使用in,那麼可以存在多行

-- 檢視年齡比“李斯文”大的學員
select * from stuinfo
where stuAge>
(select stuAge from stuInfo where stuName='李斯文');

-- 查詢出來李斯文的年齡
select stuAge from stuInfo where stuName='李斯文';

-- 檢視性別和“李斯文”一致的學員
select * from stuInfo where stuSex = (
select stuSex from stuInfo where stuName='李斯文'
);

-- 查詢“李斯文”的性別
select * from stuInfo where stuName='李斯文';

-- 刪除性別和“李斯文”一致的學員
delete from stuInfo where stuSex = (
select stuSex from stuInfo where stuName='李斯文'
);

-- 查詢年齡最大的學生資訊

-- 排序取第一
select top 1 * from stuinfo order by stuAge desc;

-- 查詢最大的年齡
select max(stuAge) from stuInfo;

-- 查詢年齡和最大年齡一致的
select * from stuInfo where stuAge=(
select max(stuAge) from stuInfo
);

--查詢年齡最小的學生資訊
select * from stuInfo where stuAge=(
select min(stuAge) from stuInfo
);

--查詢筆試成績成績最高的學生

-- 先查詢筆試成績最高的人是誰?
select top 1 stuNo from stuMarks order by writtenExam desc;

-- 查詢學生表,學生表的學號要和成績最高的那個學號相同
select * from stuInfo where stuNo=(
select top 1 stuNo from stuMarks order by writtenExam desc
);

-- 聯表
select top 1
a.stuNo,
b.stuNo,
stuName,
writtenExam
from stuInfo a inner join stuMarks b
on a.stuNo = b.stuNo order by writtenExam desc;

-- 查詢筆試成績大於全班筆試平均成績的學生記錄
-- 聚合函式不能用在where裡面
select * from stuInfo a inner join stuMarks b
on a.stuNo = b.stuNo
where writtenExam>(
select avg(writtenExam) from stuMarks
);

-- 查詢全班的平均成績
select avg(writtenExam) from stuMarks;

-- 查詢筆試成績在70分以上的學生資訊(禁止聯表)

-- 1.先查詢出來70分以上的學生的學號
select stuNO from stuMarks where writtenExam>70;

-- 2.將學號帶過去
select * from stuInfo where stuNo in (
select stuNO from stuMarks where writtenExam>70
);

-- 檢視那些人沒有考試

-- 子查詢
select * from stuInfo where stuNo not in(
select stuNo from stuMarks
);

--聯表
select * from stuInfo a left join stuMarks b
on a.stuNo = b.stuNo where ExamNo is null;

select * from stuInfo;
select * from stuMarks;

 

 

- 高階查詢

-- 聚合函式
-- sum求和,count計數,avg平均值,max最大值,min最小值

-- 分組函式 (group by)
-- where寫在 group by 之前
-- order by 寫在 group by 後面
-- select 後面只能出現分組的依據和聚合函式

-- 聯表查詢 A,B
-- 左連線 left join
-- 右連線 right join
-- 全連線 full join
-- 內連線 inner join
-- select * from A inner join B
-- on A.sid=B.stu_id

------------------------------------------

 

------------恢復內容結束------------

------------恢復內容結束------------