创建存储过程,统计每一门课程的分布情况sql语句
时间: 2023-08-05 18:45:54 浏览: 99
以下是一种可能的 SQL 存储过程语句,用于统计每一门课程的分布情况:
```
CREATE PROCEDURE course_distribution()
BEGIN
DECLARE course_name VARCHAR(50);
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT DISTINCT course_name FROM scores;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
CREATE TEMPORARY TABLE IF NOT EXISTS course_dist (
course_name VARCHAR(50),
excellent INT,
good INT,
pass INT,
fail INT
);
OPEN cur;
read_loop: LOOP
FETCH cur INTO course_name;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO course_dist (course_name, excellent, good, pass, fail)
SELECT
course_name,
SUM(CASE WHEN score >= 90 THEN 1 ELSE 0 END) AS excellent,
SUM(CASE WHEN score >= 80 AND score < 90 THEN 1 ELSE 0 END) AS good,
SUM(CASE WHEN score >= 60 AND score < 80 THEN 1 ELSE 0 END) AS pass,
SUM(CASE WHEN score < 60 THEN 1 ELSE 0 END) AS fail
FROM
scores
WHERE
course_name = course_name
GROUP BY
course_name;
END LOOP;
SELECT * FROM course_dist;
DROP TEMPORARY TABLE IF EXISTS course_dist;
CLOSE cur;
END;
```
该存储过程会创建一个游标(`cur`),遍历 `scores` 表中的不同课程名称(`course_name`),然后统计每门课程的优秀、良好、及格和不及格人数,并将结果插入到名为 `course_dist` 的临时表中。最后,该存储过程会输出 `course_dist` 表的内容,并删除该表,关闭游标。
请注意,上述代码仅供参考,具体实现可能需要根据实际情况进行调整。
阅读全文