2

我有 2 个名称kcc_201Kcc_300.

表 kcc_201 看起来像这样

ClientMarketCode | WorkDate   | OverDraft
123              | 2012-12-12 | 34.5
456              | 2012-12-12 | 60
98               | 2012-12-12 | 80

表 kcc_300 看起来像这样

ClientMarketCode | WorkDate   | DebitAmount
123              | 2012-12-12 | 80
456              | 2012-12-12 | 90
966              | 2012-12-12 | 100
100              | 2012-12-12 | 787

我的问题是什么查询让我的所有客户行都具有相同的ClientMarketCodeworkdate在 2 个表之间匹配,并且在不使用的情况下从 2 个表中检索不匹配的行union

什么查询让我得到这样的结果:

clientMarketcode | WorkDate   | OverDraft | DebitAmount
123              | 2012-12-12 | 34.5      | 80
456              | 2012-12-12 | 60        | 90
98               | 2012-12-12 | 80        | null
966              | 2012-12-12 | null      | 100
100              | 2012-12-12 | null      | 787
4

3 回答 3

4

您可以使用FULL OUTER JOIN与此类似的:

select 
    coalesce(k2.ClientMarketCode, k3.ClientMarketCode) ClientMarketCode,
    coalesce(k2.WorkDate, k3.WorkDate) WorkDate,
    k2.OverDraft,
    k3.DebitAmount
from kcc_201 k2
full outer join kcc_300 k3
  on k2.ClientMarketCode = k3.ClientMarketCode
  and k2.WorkDate = k3.WorkDate;

请参阅带有演示的 SQL Fiddle

结果是:

| CLIENTMARKETCODE |   WORKDATE | OVERDRAFT | DEBITAMOUNT |
------------------------------------------------------------
|              123 | 2012-12-12 |        34 |          80 |
|              456 | 2012-12-12 |        60 |          90 |
|               98 | 2012-12-12 |        80 |      (null) |
|              966 | 2012-12-12 |    (null) |         100 |
|              100 | 2012-12-12 |    (null) |         787 |
于 2012-12-24T13:59:25.150 回答
0
select 

isnull(kcc_201.clientMarketcode,kcc_300.clientMarketcode),
isnull(kcc_201.WorkDate,kcc_300.WorkDate),
kcc_201.OverDraft,
kcc_300.DebitAmount


from  kcc_201
FULL JOIN kcc_300 on kcc_201.clientMarketcode=kcc_300.clientMarketcode
                     and kcc_201.WorkDate=kcc_300.WorkDate
于 2012-12-24T13:58:38.747 回答
0

简单,使用 FULL OUTER JOIN,

select nullif(k1.ClientMarketCode, k2.ClientMarketCode) as ClientMarketCode,
       nullif(k1.WorkDate, k2.WorkDate) as WorkDate,
       k1.OverDraft,
       k2.DebitAmount
from kcc_201 k1 full outer join kcc_300 k2 
on k1.ClientMarketCode = k2.ClientMarketCode
and k1.WorkDate = k2.WorkDate;
于 2012-12-24T14:21:55.343 回答