简体   繁体   中英

Joining 3 Subqueries

I need a little bit of help in creating this query. I'm joining TableA and TableB and getting a value out of it; then joining TableA and TableC and getting a value out if it. Finally I am substracting both values.

I'm not sure how to write this in a single query using a lot of JOIN or if I just do 2 subqueries and then substract them.

So far I have something like:

SELECT SUM(A.quantity) From TableA JOIN Table B WHERE ...

then

SELECT SUM(A.quantity) From TableA JOIN Table C WHERE ...

Given the chance that maybe TableA and TableB have no result, but TableA and TableC does, or viceversa, or maybe both have or maybe both won't, I can't just JOIN TableA and TableB and TableC

You can do this with a cross join :

select coalesce(s1.q1, 0) - coalesce(s2.q2, 0)
from (SELECT SUM(A.quantity) as q1 From TableA JOIN Table B WHERE ...) s1 cross join
     (SELECT SUM(A.quantity) as q2 From TableA JOIN Table C WHERE ...) s2;

If one of the result sets returns NULL , the coalesce() treats the value as 0 .

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