以课本上S、 C、SC这个三个关系为例。 1:数据表创建,创建时需要创建主键约束、外键约束、用户自定义约束; 2:创建存储过程,统计每各班级某一门课程的成绩分布情况,如:0-29 几人、30-59 几人、60-79几人、80-100几人,用sql语句
时间: 2024-01-24 20:04:58 浏览: 72
好的,针对您的问题,我可以给出以下 SQL 语句:
1. 数据表创建:
```
-- 创建学生表
CREATE TABLE S (
Sno CHAR(8) PRIMARY KEY, -- 主键约束
Sname VARCHAR(20) NOT NULL,
Ssex CHAR(2) NOT NULL CHECK(Ssex IN ('男', '女')),
Sage INT,
Sdept VARCHAR(20) NOT NULL
);
-- 创建课程表
CREATE TABLE C (
Cno CHAR(4) PRIMARY KEY, -- 主键约束
Cname VARCHAR(20) NOT NULL,
Credit FLOAT NOT NULL,
Cdept VARCHAR(20) NOT NULL
);
-- 创建选课表
CREATE TABLE SC (
Sno CHAR(8) REFERENCES S(Sno), -- 外键约束
Cno CHAR(4) REFERENCES C(Cno), -- 外键约束
Grade FLOAT CHECK(Grade >= 0 AND Grade <= 100), -- 用户自定义约束
PRIMARY KEY (Sno, Cno)
);
```
2. 创建存储过程,统计每个班级某一门课程的成绩分布情况:
```
-- 创建存储过程
CREATE PROCEDURE GetGradeDistribution(
@Cno CHAR(4), -- 课程编号
@Sdept VARCHAR(20) -- 班级所在系别
)
AS
BEGIN
SELECT
CASE
WHEN Grade BETWEEN 0 AND 29 THEN '0-29'
WHEN Grade BETWEEN 30 AND 59 THEN '30-59'
WHEN Grade BETWEEN 60 AND 79 THEN '60-79'
WHEN Grade BETWEEN 80 AND 100 THEN '80-100'
END AS GradeRange, -- 成绩范围
COUNT(*) AS Count -- 人数
FROM SC
JOIN S ON SC.Sno = S.Sno
WHERE SC.Cno = @Cno AND S.Sdept = @Sdept
GROUP BY
CASE
WHEN Grade BETWEEN 0 AND 29 THEN '0-29'
WHEN Grade BETWEEN 30 AND 59 THEN '30-59'
WHEN Grade BETWEEN 60 AND 79 THEN '60-79'
WHEN Grade BETWEEN 80 AND 100 THEN '80-100'
END
END;
```
以上是针对您问题的 SQL 语句,希望对您有所帮助。
阅读全文