简体   繁体   中英

Consolidating 5 Queries into One

I have two pieces of data that I have analysed and found five distinct ways in which the data is linked. Is it possible to combine these into one query? Combining queries like these is outside my skill set, but getting these queries into a singular one would be a huge help for what I am trying to accomplish.

Here are the queries (Actual Table and Column names have been replaced)

SELECT a.Col1, d.Col2 FROM Table1 A
RIGHT JOIN Table2 B ON A.Col1=B.Col3
LEFT JOIN Table3 C ON B.Col4=C.Col5
LEFT JOIN Table4 D ON D.Col2=C.Col6;

SELECT a.Col1, d.Col2 FROM Table1 A
RIGHT JOIN Table2 B ON A.Col1=B.Col3
LEFT JOIN Table5 E ON E.Col14=B.Col4  AND Col7='Value1'
LEFT JOIN Table6 F ON E.Col8=F.Col9
LEFT JOIN Table3 C ON F.Col9=C.Col5
LEFT JOIN Table4 D ON D.Col2=C.Col6 ;

SELECT a.Col1, d.Col2 FROM Table1 A
RIGHT JOIN Table2 B ON A.Col1=B.Col3
LEFT JOIN Table7 E ON E.Col10=B.Col4  AND Col7='Value2'
LEFT JOIN Table6 F ON E.Col11=F.Col9
LEFT JOIN Table3 C ON F.Col9=C.Col5
LEFT JOIN Table4 D ON D.Col2=C.Col6 C;

SELECT a.Col1, d.Col2 FROM Table1 A
RIGHT JOIN Table2 B ON A.Col1=B.Col3
LEFT JOIN Table7 F ON F.Col10=b.Col4 AND Col7='Value3'
LEFT JOIN Table3 C ON F.Col11=C.Col5
LEFT JOIN Table4 D ON D.Col2=C.Col6 ;

SELECT a.Col1, d.Col2 FROM Table1 A
RIGHT JOIN Table2 B ON A.Col1=B.Col3
LEFT JOIN Table8 E ON E.Col12=B.Col4 AND Col7='Value4'
LEFT JOIN Table6 F ON E.Col13=F.Col9
LEFT JOIN Table3 C ON F.Col9=C.Col5
LEFT JOIN Table4 D ON D.Col2=C.Col6 ;

The result of the queries should give data like below. For any value in Col1 there could be multiple values in Col2, however, for each Col1/Col2 pairing, only 1 set of the queries above creates the link between the two entities.

Col1 | Col2
-----------
  1  |  A
  2  |  B
  2  |  C
  3  |  D
  4  |  A

Thank you for any assistance. Let me know if have any questions on the queries or results.

Note - These queries are being executed against an Oracle database.

Use:

SELECT a.Col1, d.Col2 
FROM Table2 B
LEFT JOIN Table1 A ON A.Col1=B.Col3 
LEFT JOIN Table5 H ON H.Col14=B.Col4 AND Col7='Value1'
LEFT JOIN Table7 E ON (E.Col10=B.Col4 AND Col7='Value2') OR (F.Col10=b.Col4 AND Col7='Value3')
LEFT JOIN Table6 F ON (E.Col13=F.Col9) OR (E.Col8=F.Col9) OR (E.Col11=F.Col9) OR (H.Col8=F.Col9)
LEFT JOIN Table3 C ON (B.Col4=C.Col5) OR (F.Col9=C.Col5) OR (F.Col11=C.Col5)
LEFT JOIN Table4 D ON D.Col2=C.Col6;

or a UNION operator for your select statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM