DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2004
    Posts
    1

    SQL: Join two SELECTs to calculate difference

    I 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.

  2. #2
    Join Date
    Oct 2004
    Posts
    15
    Its very hard to follow your intent from that code, could you post some table definitions and explain what exactly you want to accomplish?

  3. #3
    Join Date
    Oct 2004
    Location
    College Station TX
    Posts
    1
    Just by chance will the following query every return more than one row? If so it should be joined by an "in" clause or the query will fail.

    AND Accounts.AccountsID =
    (SELECT DISTINCT AccountsID
    FROM Transactions
    WHERE Transactions.AccountsID IN (1, 3))
    GROUP BY Accounts.AccountsID) A

    it appears that it could return two rows one for AccountsID = 1 and one for AccountsID = 3

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links