Link to home
Start Free TrialLog in
Avatar of IUFITS
IUFITS

asked on

Nested Select Statements w/ addition

Basically, I want to know if there is a way to run 2 nested select statements in a query and then take the value of those and run a calculation on them without having to re-query them (or duplicate the selects in the statement).  Attached is a simplified example of what I'd like to do, but doesn't work (my real statement is very large which is why I'm looking for a better way to do this).  Obviously, it fails on the line that adds the 2 values together because it can't use those even though I've named them.  I get that, but I'm wondering if there's a good way around it without writing a custom stored procedure or function.
Select a.ACCOUNT_NUMBER,
	(Select Sum(INCOME_CASH_AMOUNT) From TRANSACTIONS Where TRANSACTIONS.ACCOUNT_NUMBER=t.ACCOUNT_NUMBER) As INCOME_AMOUNT,
	(Select Sum(PRINCIPAL_CASH_AMOUNT) From TRANSACTIONS Where TRANSACTIONS.ACCOUNT_NUMBER=t.ACCOUNT_NUMBER) As PRINCIPAL_AMOUNT,
	(Select INCOME_AMOUNT + PRINCIPAL_AMOUNT) As TOTAL_AMOUNT
From ACCOUNT a
Inner Join TRANSACTIONS t On t.ACCOUNT_NUMBER = a.ACCOUNT_NUMBER

Open in new window

Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

what about this:
Select a.ACCOUNT_NUMBER
, Sum(t.INCOME_CASH_AMOUNT) As INCOME_AMOUNT
, Sum(t.PRINCIPAL_CASH_AMOUNT) As PRINCIPAL_AMOUNT
, Sum(t.INCOME_CASH_AMOUNT + t.PRINCIPAL_CASH_AMOUNT)As TOTAL_AMOUNT
From ACCOUNT a
Inner Join TRANSACTIONS t On t.ACCOUNT_NUMBER = a.ACCOUNT_NUMBER
group by a.ACCOUNT_NUMBER

Open in new window

Avatar of IUFITS
IUFITS

ASKER

That would work well in the simplified example I provided.  
My sub-queries are a lot larger with joins and on each that do a lot of calculating, and they're bulky text wise which makes the query difficult to read. I guess what I'm asking is, is there a way to re-use the INCOME_AMOUNT value that I've selected in another calculation (or, even in a where statement for that matter).
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg 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
Avatar of IUFITS

ASKER

Ahhhhhah!   That answers my question and gives me a good route to go on.  I'm going to accept that answer but I have one more question in that is there anything wrong with running the query like that that you can think of off the top of your head?
nothing wrong AFAIK, especially with "complex" subqueries it will save lots of code and CPU/IO ...
Avatar of IUFITS

ASKER

Thanks again angellll, it's much appreciated!