Link to home
Start Free TrialLog in
Avatar of jroof
jroof

asked on

SQL: Join two SELECTs to calculate difference

This is similar to a question I've already asked but with a new wrinkle.
 have the following query:
SELECT
CMB_AccountsID, CurrentAmount - Amount AS BalanceAmount
FROM

(SELECT SUM(Fund.Amount) AS Amount
FROM Persons
INNER JOIN Fund
ON Fund.PersonsID= Persons.PersonsID
INNER JOIN Terms
ON Terms.TermsID = Fund.TermsID
INNER JOIN Accounts
ON Accounts.PersonsID = Persons.PersonsID
WHERE Terms.Name = 'Fall 2004'
AND Accounts.AccountsID =
(SELECT DISTINCT AccountsID
FROM Transactions
WHERE Transactions.AccountsID IN (1, 3))
GROUP BY Accounts.AccountsID) A

CROSS JOIN

(SELECT SUM(Transactions.CurrentAmount) AS CurrentAmount,
Account.AccountsID
FROM Transactions
INNER JOIN Terms
ON Transactions.TermsID = Terms.TermsID
WHERE (Terms.Name = 'Fall 2004')
AND Transactions.AccountsID IN (1,3)
GROUP BY Transactions.AccountsID) B



THis query works fine if the AccountID is limited to one row, by nature of the CROSS JOIN. But when I return multiple values in the IN clause, the query will not work. I'm looking to accomplish the logic above but by another method. Any ideas would be greatly appreciated.
Avatar of ChrisFretwell
ChrisFretwell

Do you need to cross join or do you want to join on accountsid? Also, not sure you need to do all you're doing in here _ this should fix first problem, may look at your query for more after....

SELECT
CMB_AccountsID, isnull(CurrentAmount,0) - Amount AS BalanceAmount
FROM

(SELECT SUM(Fund.Amount) AS Amount
FROM Persons
INNER JOIN Fund
ON Fund.PersonsID= Persons.PersonsID
INNER JOIN Terms
ON Terms.TermsID = Fund.TermsID
INNER JOIN Accounts
ON Accounts.PersonsID = Persons.PersonsID
WHERE Terms.Name = 'Fall 2004'
AND Accounts.AccountsID =
(SELECT DISTINCT AccountsID
FROM Transactions
WHERE Transactions.AccountsID IN (1, 3))
GROUP BY Accounts.AccountsID) A

Left Join

(SELECT transactions.accountsid, SUM(Transactions.CurrentAmount) AS CurrentAmount,
Account.AccountsID
FROM Transactions
INNER JOIN Terms
ON Transactions.TermsID = Terms.TermsID
WHERE (Terms.Name = 'Fall 2004')
AND Transactions.AccountsID IN (1,3)
GROUP BY Transactions.AccountsID) B on A.accountis = b.accountsid
ASKER CERTIFIED SOLUTION
Avatar of jdlambert1
jdlambert1
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial