折叠每行的空白列

我有一张从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模板中,而且我无法在教师姓名的左边留下任何空白,只有空白才是正确的。

谢谢!

回答:

您可以逆透视,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

以上是 折叠每行的空白列 的全部内容, 来源链接: utcz.com/qa/266081.html

回到顶部