2014-10-16 57 views
0

我有一個房產所有權表,列出每個土地所有者作爲單獨的條目。爲了創建更高效​​的郵寄者,我們希望創建一個可以將配偶之間的共同所有權結合起來的觀點。配偶有相同的客戶號碼,但他們有一個單獨的地址代碼來區分個人。每個房產都有一個主要所有者,並且可以擁有任意數量的二級所有者。我需要將屬性(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' 

查詢似乎第一所有者名稱複製到當沒有第二個所有者時,這兩個名稱字段也會創建一個反轉OwnerNa的重複記錄me1和OwnerName2。我不確定在查詢中要更改什麼來解決此問題。

回答

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 
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 

如果訂單事宜(其中有時SecondaryOwnerName1Smith,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