1. 创建一个包含学生信息的表格,包括学生姓名、学号、性别、年龄、所在院系、所在班级、出生日期等字段; 2. 插入若干条学生信息; 3. 使用游标进行数据分析,例如计算全校男女比例、各院系的学生人数、各年龄段学生人数等。
时间: 2023-06-06 21:05:18 浏览: 141
学生信息管理系统,实现学生信息包括:学号、姓名、性别、年龄、班级等信息。
5星 · 资源好评率100%
这是一个关于数据库的问题,我可以回答。
1. 创建学生信息表格:
CREATE TABLE student_info (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
student_id VARCHAR(20) NOT NULL UNIQUE,
sex ENUM('男', '女') NOT NULL,
age INT NOT NULL,
department VARCHAR(20) NOT NULL,
class VARCHAR(20) NOT NULL,
birthdate DATE NOT NULL
);
2. 插入若干条学生信息:
INSERT INTO student_info (name, student_id, sex, age, department, class, birthdate)
VALUES
('张三', '1001', '男', 20, '计算机科学与技术', '1班', '2001-01-01'),
('李四', '1002', '女', 19, '计算机科学与技术', '2班', '2002-02-02'),
('王五', '1003', '男', 21, '化学与环境科学', '1班', '2000-03-03'),
('赵六', '1004', '女', 20, '化学与环境科学', '2班', '2001-04-04'),
('钱七', '1005', '男', 18, '物理与电子科学', '3班', '2003-05-05');
3. 使用游标进行数据分析,例如计算全校男女比例、各院系的学生人数、各年龄段学生人数等:
-- 计算全校男女比例
DECLARE @total_male INT;
DECLARE @total_female INT;
SELECT @total_male = COUNT(*) FROM student_info WHERE sex = '男';
SELECT @total_female = COUNT(*) FROM student_info WHERE sex = '女';
SELECT '男女比例为:' + CONVERT(DECIMAL(5,2), CAST(@total_male AS DECIMAL(10,2)) / CAST(@total_female AS DECIMAL(10,2))) AS '男女比例';
-- 计算各院系学生人数
DECLARE @department VARCHAR(20);
DECLARE @department_count INT;
DECLARE cur CURSOR FOR SELECT department FROM student_info GROUP BY department;
OPEN cur;
FETCH NEXT FROM cur INTO @department;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @department_count = COUNT(*) FROM student_info WHERE department = @department;
PRINT @department + '系学生人数为:' + CAST(@department_count AS VARCHAR);
FETCH NEXT FROM cur INTO @department;
END
CLOSE cur;
DEALLOCATE cur;
-- 计算各年龄段学生人数
DECLARE @age INT;
DECLARE @age_count INT;
DECLARE cur_age CURSOR FOR SELECT age FROM student_info GROUP BY age;
OPEN cur_age;
FETCH NEXT FROM cur_age INTO @age;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @age_count = COUNT(*) FROM student_info WHERE age = @age;
PRINT '年龄为' + CAST(@age AS VARCHAR) + '的学生人数为:' + CAST(@age_count AS VARCHAR);
FETCH NEXT FROM cur_age INTO @age;
END
CLOSE cur_age;
DEALLOCATE cur_age;
阅读全文