SQL server课程行转列并求每科最低分
时间: 2023-09-22 14:15:30 浏览: 85
好的,以下是在 SQL Server 数据库中实现课程行转列并求每科最低分的示例代码:
```sql
-- 创建原始数据表
CREATE TABLE scores (
id INT IDENTITY(1, 1) PRIMARY KEY,
name VARCHAR(50),
chinese INT,
math INT,
english INT
);
-- 插入示例数据
INSERT INTO scores (name, chinese, math, english)
VALUES
('小明', 80, 90, 70),
('小红', 90, 60, 80),
('小刚', 70, 80, 75);
-- 将课程行转列,并求每科最低分
SELECT subject, MIN(score) AS min_score
FROM (
SELECT '语文' AS subject, chinese AS score FROM scores
UNION ALL
SELECT '数学' AS subject, math AS score FROM scores
UNION ALL
SELECT '英语' AS subject, english AS score FROM scores
) AS temp
GROUP BY subject;
```
输出结果如下:
```
subject | min_score
--------+----------
语文 | 70
数学 | 60
英语 | 70
```
希望这个 SQL 代码对您有帮助!
阅读全文