--------------------上機(jī)練習(xí)1-------------------
--查詢(xún)每個(gè)年級(jí)的總學(xué)時(shí)數(shù),并按照升序排列
select gradeid as 年級(jí),sum(Classhour)
from subject
group by gradeid
order by SUM(Classhour)
--查詢(xún)每個(gè)參加考試的學(xué)員的平均分
select studentno as 學(xué)號(hào),AVG(studentresult)
from result
group by studentno
select * from subject
--查詢(xún)每門(mén)課程的平均分,并按照將序排列
select subjectid as 課程,AVG(studentresult)
from result
group by subjectid
order by AVG(studentresult) desc
--查詢(xún)每個(gè)學(xué)生參加的所有考試的總分,并按照降序排列
select studentno as 學(xué)號(hào),SUM(studentresult)
from result
group by studentno
order by SUM(studentresult) desc
---------上機(jī)練習(xí)2------------------
--查詢(xún)每學(xué)期學(xué)時(shí)超過(guò)50的課程數(shù)
use myschool
select gradeid as 年級(jí),COUNT(subjectid) as 課程數(shù)
from subject
where classhour>50
group by gradeid
--查詢(xún)課程表的所有信息
select * from subject
--查詢(xún)每學(xué)期學(xué)生的平均年齡
select * from student
select gradeid as 年級(jí),AVG(DATEDIFF(yy,birthday,getdate()))as 平均年齡
from student
group by gradeid
--查詢(xún)北京地區(qū)的每學(xué)期學(xué)生人數(shù)
select gradeid as 年級(jí),COUNT(1) as 人數(shù)
from student
where address like('%北京%')
group by gradeid
--查詢(xún)參加考試的學(xué)生中,平均分及格的學(xué)生記錄,并按照成績(jī)降序排列
select studentno,AVG(StudentResult) as 平均分
from Result
group by StudentNo
having AVG(StudentResult)>=60
order by 平均分 desc
--查詢(xún)成績(jī)表中的所有信息
select * from result
--查詢(xún)開(kāi)始日期為2014年2月22日的課程的及格平均分
select subjectid,AVG(studentresult) as 平均分
from Result
where ExamDate>='2014-2-22' and ExamDate<'2014-2-23'
group by SubjectId
having AVG(StudentResult)>=60
--統(tǒng)計(jì)至少有一次不及格的學(xué)生學(xué)號(hào)和次數(shù)。
select studentno,COUNT(1) as 次數(shù)
from Result
where StudentResult<60
group by StudentNo
注意: (1)where之后不能跟聚合函數(shù)
(2) having是對(duì)分組后的數(shù)據(jù)進(jìn)行第二次篩選或者過(guò)濾,也就是說(shuō)沒(méi)有g(shù)roup by就沒(méi)having
(3)如果語(yǔ)句中有g(shù)roup by關(guān)鍵字,那么select后只能跟group by后出現(xiàn)的列,或者是聚合函數(shù)
SQL語(yǔ)句的書(shū)寫(xiě)順序: 執(zhí)行順序:
select 列名或聚合函數(shù) (4)投影結(jié)果
from 表名 (1)定位到表
where 條件 (2)分組前的第一道過(guò)濾
group by 列名 (3)分組
having 聚合函數(shù)或者分組后的列名(5)分組后的第二道過(guò)濾
order by(6)最后排序
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com