适用行:主要适用于表头的不确定性 比如专家评分时 未评的专家不显示在表头中
关键点:数据库的列转行
下面开始实现:
1:建表
CREATE TABLE Student ( student_id int PRIMARY KEY IDENTITY(1,1), student_name varchar(20) NOT NULL ) CREATE TABLE Teacher ( teacher_id int PRIMARY KEY IDENTITY(1,1), teacher_name varchar(20) NOT NULL ) CREATE TABLE Marks ( student_id int FOREIGN KEY REFERENCES Student(student_id) ON UPDATE CASCADE ON DELETE CASCADE, teacher_id int FOREIGN KEY REFERENCES Teacher(teacher_id) ON UPDATE CASCADE ON DELETE CASCADE, PRIMARY KEY(student_id,teacher_id), mark int NOT NULL )
2:插入数据
INSERT INTO Student VALUES('李鹏') INSERT INTO Student VALUES('张三') INSERT INTO Student VALUES('小四') INSERT INTO Teacher VALUES('李老师') INSERT INTO Teacher VALUES('王老师') INSERT INTO Teacher VALUES('邓老师') INSERT INTO Teacher VALUES('不该出现的老师') INSERT INTO Marks VALUES(1,1,10) INSERT INTO Marks VALUES(1,2,20) INSERT INTO Marks VALUES(1,3,30) INSERT INTO Marks VALUES(2,1,40) INSERT INTO Marks VALUES(2,2,50) INSERT INTO Marks VALUES(3,3,60)
3:动态表查询语句
DECLARE @sql varchar(2000) SET @sql = 'SELECT student_name AS [姓名]' SELECT @sql = @sql + ',MAX(CASE teacher_id WHEN ''' + cast(A.teacher_id as nvarchar(5)) + ''' THEN mark ELSE NULL END ) AS [ ' + teacher_name + ' 评分]' FROM (SELECT DISTINCT teacher_id FROM Marks ) as A INNER JOIN Teacher ON Teacher.teacher_id = A.teacher_id SET @sql = @sql + ' FROM Marks INNER JOIN Student ON Marks.student_id = Student.student_id GROUP BY student_name' exec(@sql) print @sql
4:遇到的错误以及处理方法
①:一定要注意 该有空格的地方必须有空格,该有逗号的地方有逗号
②:下列错误是因为 A.teacher_id是 int 类型的如果没有转化为nvarchar类型