从单个表加入数据

时间:2014-10-16 21:53:00

标签: sql sql-server sql-server-2012

我有一个财产所有权表,列出每个土地所有者作为单独的条目。为了创建更有效的邮件程序,我们希望创建一个可以将配偶之间的共同所有权结合起来的视图。配偶拥有相同的客户编号,但他们有一个单独的地址代码来区分个人。每个属性都有一个主要所有者,可以拥有任意数量的二级所有者。我需要使用相同的客户编号对属性(PID)的所有者进行分组,并包括具有单独编号的属性。

例如:

╔══════════╦═══════════╦══════════╦════════════╦════════════╗
║ PID      ║ OwnerName ║ OwnerType║CustomerNum ║AdressCode  ║
╠══════════╬═══════════╬══════════╬════════════╬════════════╣
║ 100      ║Smith,John ║Primary   ║SMI001      ║   01       ║
║ 100      ║Smith,Jane ║Secondary ║SMI001      ║   02       ║
║ 100      ║Smith,Dave ║Secondary ║SMI002      ║   01       ║
║ 150      ║Jones,Rob  ║Primary   ║JON001      ║   01       ║
╚══════════╩═══════════╩══════════╩════════════╩════════════╝

应该有如下输出:

╔══════════╦═══════════╦══════════╦════════════╗
║ PID      ║OwnerName1 ║OwnerName2║CustomerNum ║
╠══════════╬═══════════╬══════════╬════════════╣
║ 100      ║Smith,John ║Smith,Jane║SMI001      ║
║ 100      ║Smith,Dave ║          ║SMI002      ║
║ 150      ║Jones,Rob  ║          ║JON001      ║
╚══════════╩═══════════╩══════════╩════════════╝

我使用了以下查询:

Select
    O1.PID as PID,
    O1.OwnerName as OwnerName1,
    O2.OwnerName as OwnerName2,
    O1.CustomerNum
From ownertable O1 left outer join
    ownertable  O2 on O1.PID = O2.PID
Where O1.CustomerNum = o2.CustomerNum AND O1.OwnerType = 'Primary Owner'

如果没有辅助所有者,查询似乎会将第一个所有者名称复制到两个名称字段中,并且它还会创建一个反转OwnerName1和OwnerName2的重复记录。我不确定在我的查询中要更改什么来解决此问题。

2 个答案:

答案 0 :(得分:1)

试试这个:

Select  pid,
        IsNull(max(case when AdressCode = '01' then OwnerName end), '') as OwnerName1,
        IsNull(max(case when AdressCode = '02' then OwnerName end), '') as OwnerName2,
        customernum
from ownertable
group by pid, customernum
Order BY pid, customernum

答案 1 :(得分:0)

听起来你正试图PIVOT你的结果。一种选择是使用MAXCASE

select pid, 
  max(case when ownertype='Primary' then OwnerName end) OwnerName1,
  max(case when ownertype='Secondary' then OwnerName end) OwnerName2,
  customernum
from ownertable
group by pid, customernum

如果订单很重要(有时候Secondary应该OwnerName1Smith,Dave一样),您可以使用row_number

with cte as (
  select pid, ownername, ownertype, customernum,
    row_number() over (partition by pid, customernum 
                       order by ownertype) rn
  from ownertable
  )
select pid, 
  max(case when rn = 1 then OwnerName end) OwnerName1,
  max(case when rn = 2 then OwnerName end) OwnerName2,
  customernum
from cte
group by pid, customernum