我们有以下表格:
表1:Student_Records
StudentID | CourseID |期间|等级
12 6010 P1 90
23 6020 P1 80
12 6030 P2''空白,没有成绩
15 6010 P1 70
12 6020 P1 80
15 6020 P1 90
表2:Course_Records
CourseID CourseDec Credits
6010数学3
6020 Biology 3
6030英语3
表3:Student_Info
StudentID FirstName LastName ClassYear
12 Joe Smith 2013
15 Chak Li 2013
23 Pete Vo 2013
结果欲望:
ClassYear LastName FirstName StudentId数学生物学
2013史密斯乔12 90 80
2013 Li Chak 15 70 90
如何使用pivot命令实现此结果?
答案 0 :(得分:0)
使用联接查询数字和课程,以便最终得到
StudentID CourseDec Grade
1 Math 20
1 Woodwork 82
透视你最终
StudentID Math WoodWork
1 20 82
然后加入Back to student获取名字Alst Name等。
答案 1 :(得分:0)
您可以使用PIVOT,但这需要您知道您感兴趣的课程说明。
SELECT p.classyear,
p.lastname,
p.firstname,
p.studentid,
pvt.math,
pvt.biology
FROM (SELECT sr.grade,
si.classyear,
si.studentid,
si.firstname,
silastname
FROM student_info si
INNER JOIN student_records sr
ON si.studentid = sr.studentid
INNER JOIN course_records cr
ON sr.courseid = cr.courseid) p PIVOT ( AVG (grade) FOR
coursedec IN (
[Math], [Biology]) ) AS pvt
ORDER BY pvt.classyear;
答案 2 :(得分:0)
DECLARE @Student_Records AS TABLE (
studentid INT,
courseid INT,
period VARCHAR(2),
grade INT);
INSERT INTO @Student_Records
VALUES (12,
6010,
'P1',
90),
(23,
6020,
'P1',
80),
(12,
6030,
'P2',
NULL),
(15,
6010,
'P1',
70),
(12,
6020,
'P1',
80),
(15,
6020,
'P1',
90);
DECLARE @Course_Records AS TABLE (
courseid INT,
coursedec VARCHAR(50),
credits INT);
INSERT INTO @Course_Records
VALUES ( 6010,
'Math',
3),
( 6020,
'Biology',
3),
( 6030,
'English',
3);
DECLARE @Student_Info AS TABLE (
studentid INT,
firstname VARCHAR(50),
lastname VARCHAR(50),
classyear INT);
INSERT INTO @Student_Info
VALUES (12,
'Joe',
'Smith',
2013),
(15,
'Chak',
'Li',
2013),
(23,
'Pete',
'Vo',
2013);
SELECT DISTINCT coursedec
FROM @Course_Records AS cr
INNER JOIN @Student_Records sr
ON sr.courseid = cr.courseid
WHERE sr.grade IS NOT NULL;
SELECT classyear,
lastname,
firstname,
summary.studentid,
summary.math,
summary.biology
FROM (SELECT *
FROM (SELECT si.studentid,
coursedec,
grade
FROM @Course_Records AS cr
INNER JOIN @Student_Records sr
ON sr.courseid = cr.courseid
INNER JOIN @Student_Info si
ON si.studentid = sr.studentid
WHERE sr.grade IS NOT NULL) AS results PIVOT (AVG(grade) FOR
coursedec
IN (
[Math], [Biology])) AS pvt) AS summary
INNER JOIN @Student_Info si
ON summary.studentid = si.studentid
请注意,您可以使用动态HTML来调整查询,因为添加了更多课程: