使用多个连接时,避免从第二行重复数据?

时间:2017-05-17 08:01:35

标签: sql-server

我正在使用如下所述的连接查询,

select rlld.lead_id,rlcm.Client_id,rlcd.CONTACT_ID,gpew.GP_EW_ID
       ,gpew.CURRENT_TYPE,gpew.CURRENT_GP_JAN 
from dbo.RS_LMS_LEAD_DETAILS rlld  
join dbo.RS_LMS_CLIENT_MASTER rlcm on rlld.CLIENT=rlcm.CLIENT_ID 
left join dbo.RS_LMS_CLIENT_CONTACT_DETAILS rlcd on rlcm.CLIENT_ID=rlcd.CLIENT_ID 
left join dbo.RS_LMS_CURRENT_GP_EW gpew on rlld.LEAD_ID=gpew.LEAD_ID 
where rlld.lead_id='SPE17051734' 

我得到的数据和我期待的数据作为图像附加, 基本上任何列都不应该从第二行重复,而应该将其设置为null或空。

Remove duplicates from each row and column, It is ok even if it null or empty

1 个答案:

答案 0 :(得分:1)

select  lead_id     = case when row_number() over (partition by rlld.lead_id order by rlcm.Client_id, rlcd.CONTACT_ID, gpew.GP_EW_ID) = 1 then rlld.lead_id end
       ,Client_id   = case when row_number() over (partition by rlld.lead_id, rlcm.Client_id order by rlcd.CONTACT_ID, gpew.GP_EW_ID) = 1 then rlcm.Client_id end
       ,CONTACT_ID  = case when row_number() over (partition by rlld.lead_id, rlcm.Client_id, rlcd.CONTACT_ID order by gpew.GP_EW_ID) = 1 then rlcd.CONTACT_ID end 
       ,gpew.GP_EW_ID
       ,gpew.CURRENT_TYPE,gpew.CURRENT_GP_JAN 
from dbo.RS_LMS_LEAD_DETAILS rlld  
join dbo.RS_LMS_CLIENT_MASTER rlcm on rlld.CLIENT=rlcm.CLIENT_ID 
left join dbo.RS_LMS_CLIENT_CONTACT_DETAILS rlcd on rlcm.CLIENT_ID=rlcd.CLIENT_ID 
left join dbo.RS_LMS_CURRENT_GP_EW gpew on rlld.LEAD_ID=gpew.LEAD_ID 
where rlld.lead_id='SPE17051734'