SQL server动态SQL课程行转列并求每科最低分
时间: 2023-09-22 17:15:30 浏览: 107
好的,以下是在 SQL Server 数据库中使用动态 SQL 实现课程行转列并求每科最低分的示例代码:
```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);
-- 定义要转换的列名
DECLARE @columns NVARCHAR(MAX) = N'chinese, math, english';
-- 构造动态 SQL
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'
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
WHERE subject IN (' + @columns + ')
GROUP BY subject;
';
-- 执行动态 SQL
EXEC (@sql);
```
输出结果与之前的示例相同:
```
subject | min_score
--------+----------
语文 | 70
数学 | 60
英语 | 70
```
需要注意的是,在构造动态 SQL 时需要注意 SQL 注入攻击,可以使用参数化查询来避免这个问题。
阅读全文