在选择中显示临时表中的字段

时间:2018-09-25 10:29:11

标签: sql sql-server

我有以下SQL。问题是它只在以下输出中显示结果:wp.gtid,wp.first_name等我也想显示来自wpe.gtid,wpe.first_name等的结果。这样我就可以轻松地并排比较各个字段。

with dups as (
    select 
          wp.GtId
        from CORE.WeccoParty wp
    where exists (select 1
                  from CORE.WeccoParty wpe
                -- where wp.Tin = wpe.Tin
                where wp.FirstName = wpe.LastName
                  and   wp.GtId     <> wpe.GtId    
              )
      )
       select distinct
      wp.GtId, 
      wp.CrmPartyId, 
      wp.LegalName, 
      wp.BusinessClass, 
      wp.RmFullName, 
      wp.PbeFullName, 
      wp.OverallClientStatus, 
     wp.OverallRpStatus, 
       wp.FirstName,
      wp.LastName,
      wp.Tin


from CORE.WeccoParty wp
join dups d on d.GtId = wp.GtId
order by 1,2

1 个答案:

答案 0 :(得分:0)

K1205,当我检查您的代码时,似乎发现duplicate entries具有相同的名字但GtId值不同

所以也许您可以对Row by Number子句使用Row_Number()函数

能否请您检查以下SQL?

select 
    ROW_NUMBER() over (Partition By wp.FirstName Order By wp.GtId) as rn,
    wp.GtId, 
    wp.CrmPartyId, 
    wp.LegalName, 
    wp.BusinessClass, 
    wp.RmFullName, 
    wp.PbeFullName, 
    wp.OverallClientStatus, 
    wp.OverallRpStatus, 
    wp.FirstName,
    wp.LastName,
    wp.Tin
from CORE.WeccoParty wp
order by wp.FirstName, rn

我希望以下CTE查询可以为您提供解决方案 重复的数据(名字和gtid)的数据在相同名字的第一个条目之后添加为新列

with rawdata as (
    select 
        ROW_NUMBER() over (Partition By wp.FirstName Order By wp.GtId) as rn,
        wp.GtId, 
        wp.CrmPartyId, 
        wp.LegalName, 
        wp.BusinessClass, 
        wp.RmFullName, 
        wp.PbeFullName, 
        wp.OverallClientStatus, 
        wp.OverallRpStatus, 
        wp.FirstName,
        wp.LastName,
        wp.Tin
    from WeccoParty wp
)
select t1.*, t2.GtId, t2.FirstName 
from rawdata as t1
inner join rawdata as t2
    on t1.FirstName = t2.FirstName and
       t1.rn <> t2.rn
where t1.rn = 1
order by t1.FirstName, t2.rn