【发布时间】:2011-06-01 06:38:56
【问题描述】:
我已将复杂架构简化为以下示例
学生
- StudentID int,姓名 varchar(50)
- 1,比尔
- 2,艾米
- 3,贝丝
- 4,斯科特
- 5,史蒂夫
类
- ClassID int、Name varchar(50)、Period varchar(50)
- 1,代数,周期1
- 2、地理、时期3
- 3,生物学,周期5
- 4,物理学,周期4
- 5,演讲,周期2
- 6、历史、时期6
还有一个联结表
学生班级
- StudentID int,ClassID int
- 1, 1
- 1, 4
- 1、5
- 2、6
- 3、5
- 3, 4
- 3、6
- 4, 1
- 4, 4
- 5, 5
- 5、6
我的目标是按时间顺序列出每个学生及其所选课程。我有以下选择
SELECT Name,Period1, Period2, Period3,
Period4, Period5, Period6
FROM (
SELECT _Students.Name AS [NAME],_Classes.Period AS PIVOT_CODE, _Classes.name as [Class]
FROM _Classes
INNER JOIN _StudentsClasses ON _Classes.ClassID=_StudentsClasses.ClassID
INNER JOIN _Students ON _StudentsClasses.StudentID=_Students.StudentID
)
AS data
PIVOT
( min([Class]) FOR [PIVOT_CODE] IN
(Period1, Period2, Period3,
Period4, Period5, Period6)
) AS pvt
结果
Name Period1 Period2 Period3 Period4 Period5 Period6
------ --------- --------- --------- --------- --------- ----------
Amy NULL NULL NULL NULL NULL History
Beth NULL Speech NULL Physics NULL History
Bill Algebra Speech NULL Physics NULL NULL
Scott Algebra NULL NULL Physics NULL NULL
Steve NULL Speech NULL NULL NULL History
我需要帮助的地方是将所有非空值移向左列,这样就没有空白了。列名可以重命名,例如
Name Choice1 Choice2 Choice3 Choice4 Choice5 Choice6
------ --------- --------- --------- --------- --------- ----------
Amy History
Beth Speech Physics History
Bill Algebra Speech Physics
Scott Algebra Physics
Steve Speech History
我可以通过将枢轴选择到临时表中然后使用游标遍历每一行/列来做到这一点,但我想避免这种情况。非常感谢任何建议。
【问题讨论】:
-
您使用的是什么 DBMS?