在SQL服务器中,我有一个名为Table Employee的表。在Employee talbe中有一个列字段名称依赖于表名。在此表中,Employee依赖于其他人。 Dependvalue值重复多次Times Dpendent Column。
Employee Name DependName
Kelly, Sean Elieen Kelly
Kelly, Sean Sienna Kelly
Kelly, Sean Elieen Kelly
Kelly, Sean Sienna Kelly
Kelly, Sean Kevin Kelly
Kelly, Sean Mark Kelly
Neuenschwander Spide kelly
Neuenschwander sumiln Kelly
在此表中,员工姓名重复多次,并且Dependent Employee也会重复多次。我有大文件。我不知道有多少dpendname是SQL文件。它采取Long Sql文件。所以我希望Table像这样.spilit on on Employee name
Employee Name DependName1 DependName2 DependName3 DependName4
Elieen Kelly Elieen Kelly Sienna Kelly Kevin Kelly Mark Kelly
Neuenschwander Spide kelly sumiln Kelly
更新:
Employee Name DependName1 DependName2 DependName3 DependName4
Kelly, Sean Elien Kelly SieeaKelly SieeaKelly SieeaKelly
我的表就像。在这个SQL大文件中,一些员工可能会有更多的DependName。如何spilit表喜欢。如何在DependName上创建Basesd列?提前谢谢
答案 0 :(得分:1)
一个简单的条件聚合与Row_Number()(或Dense_Rank()一起消除重复)可以解决这个问题如果你不需要动态
Declare @YourTable table (EmployeeName varchar(50), DependName varchar(50))
Insert Into @YourTable values
('Kelly, Sean' ,'Elieen Kelly'),
('Kelly, Sean' ,'Sienna Kelly'),
('Kelly, Sean' ,'Elieen Kelly'),
('Kelly, Sean' ,'Sienna Kelly'),
('Kelly, Sean' ,'Kevin Kelly'),
('Kelly, Sean' ,'Mark Kelly'),
('Neuenschwander','Spide kelly'),
('Neuenschwander','sumiln Kelly')
Select EmployeeName
,DependName1 = max(case when RN=1 then DependName else '' end)
,DependName2 = max(case when RN=2 then DependName else '' end)
,DependName3 = max(case when RN=3 then DependName else '' end)
,DependName4 = max(case when RN=4 then DependName else '' end)
From (
Select *,RN=Dense_Rank() over (Partition By EmployeeName Order by DependName)
From @YourTable
) A
Group By EmployeeName
返回
EmployeeName DependName1 DependName2 DependName3 DependName4
Kelly, Sean Elieen Kelly Kevin Kelly Mark Kelly Sienna Kelly
Neuenschwander Spide kelly sumiln Kelly