本人经常写sql server脚本,有时需要行转列,这里做个笔记。
练习脚本-- 学生表
CREATE TABLE student (
stuid VARCHAR(16) NOT NULL,
stunm VARCHAR(20) NOT NULL,
PRIMARY KEY (stuid)
);
-- 课程表
CREATE TABLE courses (
courseno VARCHAR(20) NOT NULL,
coursenm VARCHAR(100) NOT NULL,
PRIMARY KEY (courseno)
);
-- 成绩表
CREATE TABLE score (
stuid VARCHAR(16) NOT NULL,
courseno VARCHAR(20) NOT NULL,
scores FLOAT NULL DEFAULT NULL,
PRIMARY KEY (stuid, courseno)
);
-- 插入数据
-- 学生表数据
Insert Into student (stuid, stunm) Values('1001', '张三');
Insert Into student (stuid, stunm) Values('1002', '李四');
Insert Into student (stuid, stunm) Values('1003', '赵二');
Insert Into student (stuid, stunm) Values('1004', '王五');