I have a tables A
, B
and C
with a lot of columns (30+). Main columns for all are Id
, RefNumber
Also I have table LinkedEntity
where I can match records from different tables (A
, B
or C
)
I need to select all records from table A
and also display linked records from B
and C
A
Id | RefNumber | OtherColumns |
---|---|---|
101 | A101 | ... |
102 | A102 | ... |
B
Id | RefNumber | OtherColumns |
---|---|---|
201 | B101 | ... |
202 | B102 | ... |
C
Id | RefNumber | OtherColumns |
---|---|---|
301 | C101 | ... |
302 | C102 | ... |
LinkedEntity
Id | EntityId | LinkedEntityId |
---|---|---|
1 | 101 | 202 |
2 | 102 | 301 |
3 | 102 | 201 |
4 | 102 | 202 |
Expected result:
Id | RefNumber | LinkedB | LinkedBRefNumb | LinkedC | LinkedCRefNumb |
---|---|---|---|---|---|
101 | A101 | 202 | B102 | NULL | NULL |
102 | A102 | 201,202 | B101,B102 | 301 | C101 |
First idea to write something like
SELECT A.Id, A.RefNumber, L1.Id, L1.RefNumber, L2.Id, L2.RefNumber
FROM A
LEFT JOIN (SELECT B.Id, B.RefNumber, le.EntityId, le.LinkedEntityId FROM B JOIN LinkedEntity le ON le.EntityId = B.Id OR le.LinkedEntityId = B.Id) L1
ON A.Id = L1.EntityId OR A.Id = L1.LinkedEntityId
LEFT JOIN (SELECT C.Id, C.RefNumber, le.EntityId, le.LinkedEntityId FROM C JOIN LinkedEntity le ON le.EntityId = C.Id OR le.LinkedEntityId = C.Id) L2
ON A.Id = L2.EntityId OR A.Id = L2.LinkedEntityId
But this query returns duplicates records of A
table.
Is there any way to remove duplicates and have joined values of linkedEntities? (Maybe using STRING_AGG
) ?