加入和取消多个表格

时间:2017-08-10 10:20:23

标签: sql join unpivot

我有两张桌子:

更正表:

C_CORRECTIONS
CorrAmount  |HalfYear1  |HalfYear2  |Type   |REFNUM |
-----------------------------------------------------
1000        |50         |50         |HYINT  |R123   |

收集表:

P_COLLECTED
Amount      |Type   |Account    |REFNUM |
-----------------------------------------
1500        |TOTAL  |ACCT1      |R123   |
50          |HYINT  |ACCT2      |R123   |
50          |HYINT  |ACCT3      |R123   |

我需要的是:

CorrAmount  |Type   |Account    |REFNUM |
-----------------------------------------
1000        |TOTAL  |ACCT1      |R123   |
50          |HYINT  |ACCT2      |R123   |
50          |HYINT  |ACCT3      |R123   |

我在下面尝试过:

SELECT DISTINCT C.AMT, P.ACCOUNT,C.REFNUM FROM (
SELECT U.AMT, U.Type, REFNUM
FROM C_CORRECTIONS
UNPIVOT
(
  AMT
  FOR INT_AMT IN (CorrAmount,HalfYear1,HalfYear2)
) U
) C
LEFT JOIN P_COLLECTED P
ON C.REFNUM = P.REFNUM AND C.AMT = P.Amount;

结果:

AMT     |ACCOUNT    |REFNUM |
--------|-----------|-------|
50      |ACCT2      |R123   |
50      |ACCT3      |R123   |
1000    |           |R123   |

编辑:好的。所以我使用了左连接而不是连接,并且放入了不同的并且我获得了主要数量,但我似乎无法获得它的帐户。

2 个答案:

答案 0 :(得分:1)

您将C_CORRECTIONS取消,然后将P_COLLECTED加入其中。

但也许你可以从P_COLLECTED开始并加入C_CORRECTIONS 由于P_COLLECTED已经有多行。

测试示例:

declare @P_COLLECTED table (Amount int, Type varchar(8), Account varchar(8), REFNUM varchar(8));
declare @C_CORRECTIONS table (CorrAmount int, HalfYear1 int, HalfYear2 int, Type varchar(8), REFNUM varchar(8));

insert into @P_COLLECTED (Amount, Type, Account, REFNUM) values
(1500,'TOTAL','ACCT1','R123'),
(50  ,'HYINT','ACCT2','R123'),
(50  ,'HYINT','ACCT3','R123');

insert into @C_CORRECTIONS (CorrAmount, HalfYear1, HalfYear2, Type, REFNUM) values
(1000,24,26,'HYINT','R123');

select 
(case when t.Type = 'TOTAL' then c.CorrAmount else t.Amount end) as Amount,
t.Type, t.Account, t.REFNUM
-- , c.*
from @P_COLLECTED t
left join @C_CORRECTIONS c 
      -- on (t.REFNUM = c.REFNUM and t.Type in ('TOTAL',c.Type));
      on (t.REFNUM = c.REFNUM and t.Type = 'TOTAL');

答案 1 :(得分:0)

您好我已经修改了您的脚本,请验证

Select  Amount, 
        Type,
        'Acct' + CAST(ROW_NUMBER()OVER(PARTITION BY  Refnum  ORDER BY (Select  NULL))AS VARCHAR(20))Account,REFNUM 
                from  
            (Select Amount, Type, REFNUM from  @Table2 where type = 'Total'
                    UNION ALL
            SELECT C.AMT, C.Type,C.REFNUM FROM (
            SELECT U.AMT, U.Type, REFNUM
            FROM @Table1
            UNPIVOT
            (
              AMT
              FOR INT_AMT IN (CorrAmount,HalfYear1,HalfYear2)
            ) U
            ) C,@Table2 P
            WHERE C.REFNUM = P.REFNUM OR  C.AMT = P.Amount
            GROUP BY C.AMT, C.Type,C.REFNUM)T