【问题标题】:Join Data from single table连接单个表中的数据
【发布时间】:2014-10-17 09:58:11
【问题描述】:

我有一个财产所有权表,将每个土地所有者列为单独的条目。为了创建更高效​​的邮件程序,我们希望创建一个可以结合配偶之间共同所有权的视图。配偶有相同的客户编号,但他们有一个单独的地址代码来区分个人。每个财产都有一个主要所有者,并且可以有任意数量的次要所有者。我需要将具有相同客户编号的财产 (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。我不确定要在我的查询中更改什么来解决此问题。

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      听起来您正在尝试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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多