为下面的场景提供Sql查询

时间:2014-06-24 09:14:46

标签: sql sql-server

TeamName        Patient Name         Staff Name
Team 1C DMAC                         Sabirah Bibi
Team 1C DMAC                         Shubhi Rastogi
Team 1C DMAC    Andy Proctor    
Team 1C DMAC    Lynn Ashurst    

这四个需要像这样改变

TeamName        Patient Name             Staff Name
Team 1C DMAC    Andy Proctor             Sabirah Bibi
Team 1C DMAC    Lynn Ashurst             Shubhi Rastogi

感谢您提前更新Sql查询

2 个答案:

答案 0 :(得分:0)

试试这个

update t
    Set staffname = b.Staffname
    from 
    (
    Select teamname,patientname,row_number() over(order by teamname) 'id'
    from   Team
    where  staffname is null
    ) a
    join 
    (
    Select teamname,staffname,row_number() over(order by teamname) 'id'
    from team 
    where patientname is null
    ) b
    on a.teamname=b.teamname and a.id=b.id
    join team t
    on  t.teamname = a.teamname and t.patientname = a.patientname
    where t.staffname is null

    Delete from team where patientname is null

答案 1 :(得分:0)

create table #temp
(
TeamName        varchar(50),
PatientName         varchar(100),
StaffName varchar(200)
)
insert into #temp
select 'Team 1C DMAC ','','Sabirah Bibi'

union

select 'Team 1C DMAC ','','Shubhi Rastogi'

union

select 'Team 1C DMAC ','Andy Proctor',''

union

select 'Team 1C DMAC ','Lynn Ashurst',''

union

select 'Team 1C DMAC ','Lynn Ashurst','Andy Proctor'



update #Temp set StaffName=T1.StaffName from #Temp

inner join 
(

select T1.Patientname,T2.StaffName,T1.TeamName from 
(

select TeamName,PatientName,StaffName,Row_number() over(partition by TeamName order by 
PatientName) as ID from #temp
where StaffName ='' or Patientname !=''

) as T1

inner join 

(

select TeamName,PatientName,StaffName,Row_number() over(partition by TeamName order by 
PatientName) as Id from #temp
where StaffName !='' or Patientname =''

) as T2

on (T1.Id= T2.Id and (T1.StaffName='' or T2.patientName='') and T1.TeamName=T2.Teamname)
or(T1.StaffName!='' and T2.patientName!='' and T1.TeamName=T2.Teamname)

) as T1

on #Temp.TeamName=T1.TeamName
and #Temp.PatientName=T1.PatientName
and #Temp.StaffName=''

delete from #temp where patientName=''

select * from #temp'