SQL与另一个表的连接导致重复的记录

时间:2019-06-01 20:24:11

标签: sql sql-server

我正在尝试合并两个表。

表A:

RowID   Name        Active
4       Bangalore   1

表B:

Sno  RowID  Type     Stores      Active
1    4      Legal    Center-A    1
2    4      Trade    Center-A01  1
3    5      Trade    Center-B    1

此处RowID是表A的外键。 如果类型为Legal,则LegalName应该为Center_A,并且 如果“类型”为“贸易”,则“贸易名称”应为Center_A01

这是我尝试过的方法,但是我得到了两行,分别是Legal和Trade Type。

Name        Type      LegalName  TradeName   
Bangalore   Legal     Center-A   Center-A01
Bangalore   Trade     Center-A   Center-A01

我真正需要的是下面的东西

 Name        LegalName  TradeName   
 Bangalore   Center-A   Center-A01

在这种情况下是否需要使用CASE?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

要实现此目的,您可以进行2次连接,其中1次用于trade,第二次进行legal

select
     a.[Name]
    ,legal.[Stores] as LegalName
    ,trade.[Stores] as TradeName
from TableA a
join TableB trade
    on a.RowID = trade.RowID
    and trade.[Type] = 'Legal'
join TableB legal
    on a.RowID = legal.RowID
    and trade.[Type] = 'Trade'