我有一个从Excel电子表格导入的大表。对于包含教师姓名的五个列,我想要折叠每行中的所有空白,这样我就没有任何名字左边的空白。一个例子可能会更好地表明我的意思。
以下是数据的示例:
Student ID Teacher1 Teacher2 Teacher3 Teacher4 Teacher5
445633 Mary Deb Juan
876302 Trevor Juan Mary Val Deb
659404 Luo Trevor
535485 Deb
775431 Val Luo
565002 Luo Mary Juan
我想把左边的空白折叠起来,所以看起来像这样:
Student ID Teacher1 Teacher2 Teacher3 Teacher4 Teacher5
445633 Mary Deb Juan
876302 Trevor Juan Mary Val Deb
659404 Luo Trevor
535485 Deb
775431 Val Luo
565002 Luo Mary Juan
我必须这样做,因为我会把它粘贴到一个国家规定的Excel模板中,我不能在教师姓名的左边留下任何空白,只有在右边空白。
谢谢!
答案 0 :(得分:2)
你可以在教师和枢轴上取消透视,ROW_NUMBER()再次......即:
declare @t1 as table (StudentID int, Teacher1 nvarchar(100), Teacher2 nvarchar(100), Teacher3 nvarchar(100), Teacher4 nvarchar(100), Teacher5 nvarchar(100));
insert into @t1 values (445633,'Mary',NULL,'Deb','Juan',NULL),(876302,'Trevor','Juan','Mary','Val','Deb'),
(659404,'Luo',NULL,NULL,NULL,'Trevor'),(535485,NULL,NULL,NULL,'Deb',NULL),
(775431,NULL,NULL,'Val',NULL,'Luo'),(565002,NULL,NULL,'Luo','Mary','Juan');
with UnpivotT as (
SELECT StudentID, TeacherName, TeacherColumn as OriginalColumn
from @t1 unpivot (
TeacherName for TeacherColumn in ([Teacher1],[Teacher2],[Teacher3],[Teacher4],[Teacher5])
) uT
), NewColumnT as (
select StudentID, TeacherName, 'Teacher'+(
convert(nvarchar(100), ROW_NUMBER() OVER (PARTITION BY StudentID ORDER BY OriginalColumn))
) as NewColumn
from UnpivotT
)
select *
from NewColumnT
pivot (
max(TeacherName) for NewColumn in ([Teacher1],[Teacher2],[Teacher3],[Teacher4],[Teacher5])
) as pivotT