如何查找没有uniqueID的两个查询之间的差异

时间:2012-07-12 17:12:15

标签: sql sql-server-2008

我使用以下查询尝试查找两个数据库的查询结果之间的差异。我无法将AccountID用作比较点,因为它们不在不同数据库之间排列。 ctes中的选择都返回200105行,但cte上的连接结果为201779行。在这种情况下,数据应该能够匹配。我是否在正确的轨道上?如果是这样,我错过了什么,或者我应该采用不同的方法。

    with cteDev3 (AccountID, SecurityID, UniqueAccountID, BuyPrice, BuyDate, Shares)as
      (select Al.AccountID, al.SecurityID,ad.UniqueAccountId, BuyPrice, BuyDate, Shares
        from dev3TMAd.dbo.AccountLot al
        join dev3TMAd.dbo.AccountDetails ad
        on al.AccountID = ad.AccountId
        where ad.EnterpriseId = 'HuberFinancial'),
    cteTest2 (AccountID, SecurityID, UniqueAccountID, BuyPrice, BuyDate, Shares)as
       (select Al.AccountID, al.SecurityID,ad.UniqueAccountId, BuyPrice, BuyDate, Shares
        from test2TMAd.dbo.AccountLot al
        join test2TMAd.dbo.AccountDetails ad
        on al.AccountID = ad.AccountId
        where ad.EnterpriseId = 'HuberFinancial')

select c3.UniqueAccountId as 'Dev3' , t2.UniqueAccountId as 'Test2'
from cteTest2 t2
join cteDev3 c3
    on c3.UniqueAccountId = t2.UniqueAccountId
    and c3.SecurityID = t2.SecurityID
    and c3.BuyDate = t2.BuyDate
    and c3.Shares = t2.Shares
    and c3.BuyPrice = t2.BuyPrice

这是作为ctes一部分的子查询的结果集:

AccountID | SecurityID | UniqueAccountId | BuyPrice | BuyDate | Shares
949662 | 17030 | 11284035 | 42.690021 | 2007-12-19 00:00:00 | 4.710000
949662 | 17030 | 11284035 | 42.690629 | 2007-12-19 00:00:00 | 13.521000
949662 | 17030 | 11284035 | 42.611940 | 2007-12-19 00:00:00 | 0.134000
949662 | 17030 | 11284035 | 39.323467 | 2008-03-10 00:00:00 | 0.946000
949662 | 17030 | 11284035 | 40.831884 | 2008-06-10 00:00:00 | 6.323000
949662 | 17030 | 11284035 | 30.730860 | 2008-09-09 00:00:00 | 6.335000
949662 | 17030 | 11284035 | 16.290063 | 2008-12-10 00:00:00 | 111.045000
950091 | 25885 | 11937183 | 14.629975 | 2012-03-23 00:00:00 | 12.337000
950091 | 25885 | 11937183 | 14.599671 | 2012-04-23 00:00:00 | 12.140000
950091 | 4325 | 11937183 | 11.082955 | 2012-01-27 00:00:00 | 6768.953000
950091 | 4325 | 11937183 | 11.119163 | 2012-01-31 00:00:00 | 1.242000

1 个答案:

答案 0 :(得分:1)

我认为你想做一个完整的外连接,以便找到那些不匹配的连接:

select (case when c3.UniqueAccountId is not null and t2.UniqueAccountId is not null
             then 'MATCH'
             when c3.UniqueAccountId is not null then 'DEV-ONLY'
             when t2.UniqueAccountId is not null then 'TEST-ONLY'
             else 'Oops!'
        end) as MatchType,
       c3.UniqueAccountId as 'Dev3', t2.UniqueAccountId as 'Test2'
from cteTest2 t2 full outer join
     cteDev3 c3
     on c3.UniqueAccountId = t2.UniqueAccountId and
        c3.SecurityID = t2.SecurityID and
        c3.BuyDate = t2.BuyDate and
        c3.Shares = t2.Shares and
        c3.BuyPrice = t2.BuyPrice