将数据从一列拆分为多列

时间:2012-05-18 15:26:45

标签: sql tsql etl

我有一张满是学生出勤数据的表格,我们正在迁移到另一个学生信息系统,他们想要平面文件的方式是每个学生每天排成一行,列出所有7个学期。现在我们的数据每个时期每天存储为一条记录(参见附件架构)格式化这些数据的最佳方法是什么,以匹配我上面列出的内容。我还附上了他们想要的截图(每行都是一列)。

添加了数据的屏幕截图。

Our current Database Schema

What it needs to be

enter image description here

2 个答案:

答案 0 :(得分:1)

看看PIVOT和UNPIVOT。

Here就是一个例子

答案 1 :(得分:0)

好的,所以枢轴不是我需要的。我最后和同事讨论了我的问题,他告诉我要使用子查询。所以这就是我解决它的方法!

select distinct student_id,school_year,school_number,absent_date,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='H') as daily_code,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='1') as per_1,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='2') as per_2,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='3') as per_3,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='4') as per_4,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='5') as per_5,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='6') as per_6,
(select absent_code from attend_student_detail a2 where a2.student_id=a.student_id and a2.absent_date=a.absent_date and a2.absent_period='7') as per_7 

FROM attend_student_detail a

Order By Absent_Date, Student_ID
相关问题