根据两个字段获取记录之间的1:1匹配,然后将它们组合在一起?

时间:2012-11-14 01:59:52

标签: sql tsql

我有两张这样的表:

Date    Client  Amount | table x
123     abc     123
456     abc     987
234     xyz     567


Date    Client  Amount | table y
123     abc     234
921     lka     981
234     xyz     123

在我的查询中,我想显示:

123     abc     123     | (from x)
123     abc     234     | (from y)
234     xyz     567     | x
234     xyz     123     | y

在没有“合作伙伴”的情况下退出所有记录。这在TSQL中是否可行?

2 个答案:

答案 0 :(得分:2)

SELECT a.[Date] , a.[Client] , a.[Amount], 'X' [table]
FROM   tableX a INNER JOIN tableY b 
          ON a.[DATE] = b.[DATE] AND
             a.[Client] = b.[Client]
UNION
SELECT a.[Date] , a.[Client] , a.[Amount], 'Y' [table]
FROM   tableY a INNER JOIN tableX b 
          ON a.[DATE] = b.[DATE] AND
             a.[Client] = b.[Client]
ORDER BY [DATE], [Table]

答案 1 :(得分:2)

    select DISTINCT
           case when c='x' then x.date else y.date end date,
           case when c='x' then x.client else y.client end client,
           case when c='x' then x.amount else y.amount end amount,
           c from_
      from tablex x
      join tabley y on x.date=y.date and x.client=y.client
cross join (select 'x' union all select 'y') z(c)
  order by date, client, from_;

可接受解决方案的替代方案。

请注意,如果您有两个/两个表中的多个匹配项,那么“x”的所有结果将在“y”匹配之前列出。 e.g。

create table tablex (Date int, Client char(3), Amount int);
insert tablex select
    123     ,'abc',     123 union all select
    456     ,'abc',     987 union all select
    123     ,'abc',     919 union all select
    234     ,'xyz',     567;
create table tabley (Date int, Client char(3), Amount int);
insert tabley select
    123     ,'abc',     234 union all select
    123     ,'abc',     867 union all select
    921     ,'lka',     981 union all select
    234     ,'xyz',     123;

**Results**

date        client amount      from_
----------- ------ ----------- -----
123         abc    123         x
123         abc    919         x
123         abc    234         y
123         abc    867         y
234         xyz    567         x
234         xyz    123         y