如果ID相同并保留每行的唯一信息,则T-SQL合并行

时间:2013-08-22 14:26:11

标签: sql tsql

我有一张表格,可以提取个人和组织的名称和地址。有时在此表中,个人将拥有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);

我确信这不是找到重复合并回到另一行的最佳方法。我很欣赏任何想法。

1 个答案:

答案 0 :(得分: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;