0

我有两个这样的表:

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 中可能吗?

4

2 回答 2

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]
于 2012-11-14T02:09:00.103 回答
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”的匹配项之前。例如

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
于 2012-11-14T02:16:36.783 回答