如何连接具有两个公共列值的两个表并将其余列合并

时间:2018-04-11 02:20:35

标签: sql

我想在下面的链接中结合表A和表B,最后得到表C.在SQL中执行此操作的最佳方法是什么?我已经考虑过在LedgerID + Year的表之间创建一个复合键,进行内连接,然后联合左右数据。我还很好奇如何避免跨行重复值,例如Balance = 50.00,最后是Tires和Windshield的行。

enter image description here

4 个答案:

答案 0 :(得分:1)

尝试完整的外部联接,加入LedgerID和Year,使用coalesce在表A为NULL时显示表B' LedgerID / Year:

SELECT 
COALESCE(A.LedgerID, B.LedgerID) as LedgerID,
COALESCE(A.Year, B.Year) as Year,
A.Title,
A.Payment,
B.Balance
FROM "Table A" AS A
FULL OUTER JOIN "Table B" AS B ON (A.LedgerID=B.LedgerID AND A.Year=B.Year)

答案 1 :(得分:0)

- 请尝试此查询。由于您只参考了LedgerId和Year,因此轮胎和轮胎的余额将显示为50。挡风玻璃

; with cte_Ledger (LedgerId, [year])
AS
(
Select DISTINCT LedgerId, [year]
From tableA
UNION
Select DISTINCT LedgerId, [year]
From tableB
)
select t.LedgerId
        , t.[year]
        , t1.Title
        , T1.Payments
        , t2.Balance
FROM cte_Ledger t
left join tableA t1 on t.LedgerId = t1.LedgerId  and t.[year] = t1.[year]
left join tableB  t2 on t2.LedgerId = t.LedgerId and t2.[year] = t.[year]

答案 2 :(得分:0)

我是这么认为的,以上查询无助于获得预期的结果。 一些误解是有要求的。 对于ledgerid = 22和Year = 2017,表-A中有2条记录,表-B中有1条记录。但是在期望结果中,Balance 50(表-B的记录)仅存在与表-A的匹配的第一行。按照上述所有逻辑,它将有2个记录,其中ledgerid = 22,年= 2017,标题为“轮胎”& “的挡风玻璃”。

如果需要与上述相同的结果,则需要使用递归CTE 或排序函数,其顺序为 ID 列。

答案 3 :(得分:0)

这是我加载表后的解决方案,另一个嵌套的case语句可能需要格式化Ledger 24上的零。

Select 
[LedgerID],
[Year],
Case when PayRank = 1 then Title else ''  end as Title,
Case when PayRank = 1 then convert(varchar(20),Payments) else '' end as 
Payments,
Case when BalRank = 1 then convert(varchar(20),Balance) else '' end as 
Balance
from(

SELECT 
  B.[LedgerID]
  ,B.[Year]
  ,Rank()Over(Partition by B.LedgerID,Payments order by 
   B.LedgerID,B.Year,Title) as PayRank
  ,isnull([Title],'') as Title
  ,isnull([Payments],0) as Payments
  ,Rank()Over(Partition by B.LedgerID,B.Year order by 
   B.LedgerID,B.Year,Payments) as BalRank
  ,Balance
   FROM [TableB] B
   left outer join [TableA] A
   on A.LedgerID = B.LedgerID 
    ) Query
   order by LedgerID,Year

enter image description here