3

我有一张表格,其中包含个人和组织的名称和地址。有时在此表中,个人将有 2 个地址(一个家庭和另一个企业),因此会返回两次。其他时候他们只能有一个地址。

AccountNum     Name        Contact    AddressLine1        City    County    State    Zip        AddrType     IndivOrBuss
321          Dilbert Law   Mr.Dilbert   123 Merrwood     Pittsburgh   NULL       PA    15212      Home          Business
321          Dilbert Law   Mr.Dilbert   321 Dogbert Dr.  Pittsburgh   NULL       PA    15212      Bussiness     Business

我必须拿这张表并使它适合另一个表,同时保留两个地址并且每个 AccountNum 只有一行。这些行需要合并以显示地址和唯一字段。它应该看起来像这样:

AccountNum     Name        Contact    AddressLine1        City       County  State   Zip        AddrType     IndivOrBuss   Address2Line1       2ndCity    2ndCounty 2ndState     2ndZip     2ndAddrTyp
321          Dilbert Law   Mr.Dilbert   123 Merrwood     Pittsburgh   NULL     PA    15212      Home          Business     321 Dogbert Dr.  Pittsburgh     NULL       PA         15212      Bussiness     

我不确定如何在保留那些不需要合并的同时进行合并。

我已经通过使用拉出了需要合并的那些

FROM Address WHERE Address.[AccountNum] IN 
(Select Address.[AccountNum] 
   From Address
Group by Address.[AccountNum] 
   having count(*)>1);

我敢肯定这不是找到重复项以合并回另一行的最佳方法。我会很感激任何想法。

4

1 回答 1

2

我同意您需要将表连接到自身,但您还需要左连接以不排除单个地址,并且我添加了行 ID 以消除重复行。

WITH Address AS
(
    SELECT
     *
    ,ROW_NUMBER() OVER(PARTITION BY AccountNum ORDER BY AccountNum) AS RowID
    FROM AddressTable
)
SELECT
 a1.AccountNum
,a1.Name
,a1.Contact
,a1.AddressLine1
,a1.City
,a1.County
,a1.State
,a1.Zip
,a1.AddrType
,a1.IndivOrBuss
,a2.AddressLine1 AS AddressLine2
,a2.City AS [2ndCity]
,a2.County AS [2ndCounty]
,a2.State AS [2ndState]
,a2.Zip AS [2ndZip]
,a2.AddrType AS [2NDAddrType]
FROM Address a1
LEFT JOIN Address a2
ON a1.AccountNum=a2.AccountNum
AND (a1.AddressLine1!=a2.AddressLine1
        OR a1.City!=a2.City
        OR a1.County!=a2.County
        OR a1.State!=a2.State
        OR a1.Zip!=a2.Zip
        OR a1.AddrType!=a2.AddrType)
WHERE a1.RowID=1;
于 2013-08-22T17:05:36.220 回答