Join 连接两个数据透视表

Join 连接两个数据透视表,join,pivot,Join,Pivot,我在MS SQL Server 2012中有两个查询: **Query for Uploads:** select Contract_Code, [201612] as '201612',[201701] as '201701', [201702] as '201702' from (select OrderID, Creation_Date_YYYYMM, Contract_Code from Raw_Data_A) p pivot(count(OrderID) for Cre

我在MS SQL Server 2012中有两个查询:

**Query for Uploads:**    
select Contract_Code, [201612] as '201612',[201701] as '201701', [201702] as '201702' from (select OrderID, Creation_Date_YYYYMM, Contract_Code from Raw_Data_A) p
    pivot(count(OrderID) for Creation_Date_YYYYMM in ([201612],[201701],[201702])) as pvt
    order by Contract_Code


**Query for REal Orders:**    
select Contract_Code, [201612] as '201612',[201701] as '201701', [201702] as '201702' from (select OrderID, concat(year([Creation_Date]),format([Creation_date],'MM')) as Creation_Date_YYYYMM, Contract_Code from Raw_Data_B) p2
    pivot(count(OrderID) for Creation_Date_YYYYMM in ([201612],[201701],[201702])) as pvt
    order by Contract_Code
每种方法都会产生如下结果:

Contract_Code   201612  201701  201702
Contract1   3   1   0
Contract2   17  0   6
Contract3   23  8   14
Contract4   48  45  6
我想加入他们,以实现以下成果:

             201612     201701  201702  
ContractNameRealUploadRealUploadRealUpload
Contract1   23  24  35  26  27  28
Contract2   24  45  36  26  27  28
Contract3   25  45  37  26  27  28
Contract4   26  45  38  26  27  28
Contract5   27  45  39  26  27  28
Contract6   28  45  40  26  27  28
Contract7   29  45  41  26  27  28
Contract8   30  45  42  26  27  28
Contract9   31  45  43  26  27  28
Contract10  32  45  44  26  27  28

希望你能帮助我。谢谢

它使用以下代码:

select coalesce(a.Contract_Code,b.Contract_Code),b.[201612],a.[201612],b.[201701],a.[201701],b.[201702],a.[201702] from

(select Contract_Code, [201612] as '201612',[201701] as '201701', [201702] as '201702' from (select OrderID, Creation_Date_YYYYMM, Contract_Code from Raw_Data_A) as b
pivot(count(OrderID) for Creation_Date_YYYYMM in ([201612],[201701],[201702])) as pvt) a


full join

(select Contract_Code, [201612] as '201612',[201701] as '201701', [201702] as '201702' from (select OrderID, concat(year([Creation_Date]),format([Creation_date],'MM')) as Creation_Date_YYYYMM, Contract_Code from Raw_Data_B) as b
pivot(count(OrderID) for Creation_Date_YYYYMM in ([201612],[201701],[201702])) as pvt) b

on a.Contract_Code=b.Contract_Code
order by coalesce(a.Contract_Code,b.Contract_Code);