2012-11-14 48 views

回答

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 
+0

您的解決方案不太直觀,但功能更多。謝謝! – Kyle

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] 
+0

令人驚歎。謝謝! – Kyle

相關問題