避免在SQL JOIN上重复

时间:2019-07-12 15:51:04

标签: sql

我有两个如下表

Table A
ID   ID_Name    Amount
------------------------
1    ABC        200
2    XYZ        300

Table B
ID    Role    Name 
------------------
1     Plumber   John
1     Estimator  Redmond 

我想同时连接两个表,并且需要以下结果


ID ID_Name  Plumber Estimator   Amount
--------------------------------------
1   ABC     John      Redmond   200

我正在使用的SQL加入

Select A.ID, A.ID_Name

CASE WHEN B.Role='Plumber' THEN B.Name END AS Plumber,
CASE WHEN B.Role='Estimator' THEN B.Name END AS Estimator,
A.Amount
FROM A A
INNER JOIN B B ON A.ID=B.ID

```
How I can achieve this, when am trying to join I am getting two lines for the same ID and if do group by amount is 400

2 个答案:

答案 0 :(得分:5)

您应该两次加入tableb,一次是Plumber,另一次是estimator

select a.ID,  a.ID_Name, b1.name plumber, b2.name estimator, a.amount
from tableA a
inner join tableb b1 on a.id = b1.id and b1.role ='Plumber'
inner join tableb b2 on a.id = b2.id and b2.role ='Estimator'

如果有重复的行,则应使用不同的

select distinct  a.ID,  a.ID_Name, b1.name plumber, b2.name estimator, a.amount
from tableA a
inner join tableb b1 on a.id = b1.id and b1.role ='Plumber'
inner join tableb b2 on a.id = b2.id and b2.role ='Estimator'

答案 1 :(得分:0)

虽然@scaisEdge可以在给定的情况下工作,但我想您必须重新考虑表B的架构。期望的结果是动态的。现在,使用上面给出的查询,您将排成一行。如果引入另一个新角色会发生什么?

如果Plumber和Estimator是给定ID的强制实体,而不仅仅是TableB.Role可能像TableB.Plumber,TableB.Estimator一样重新设计。