Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2 Aggregate (Sum) Queries and Union 1

Status
Not open for further replies.

MCCooper

MIS
Aug 13, 2002
20
AU
I am using a Union statement to combine 2 aggregate (sum) select statements but I really want to sum the whole lot where the ParentID is the same number.

My statement as it stands is:

SELECT Ref_Code AS ParentID,
SUM(LMR_CurrentLoanBal) AS CurrentLoanBalance
FROM Loan_MasterReference
WHERE ISNULL(LMR_KeyIDLink,0) = 0
GROUP BY Ref_Code

UNION ALL

SELECT LMR_KeyIDLink AS ParentID,
SUM(LMR_CurrentLoanBal) AS CurrentLoanBalance
FROM Loan_MasterReference
WHERE ISNULL(LMR_KeyIDLink,0) <> 0
GROUP BY LMR_KeyIDLink
ORDER BY Ref_Code

Any help will be much appreciated.

Thanks

Matt
 
Code:
[code]
select parentId,sum(CurrentLoanBalance)
from (
SELECT Ref_Code AS ParentID,
SUM(LMR_CurrentLoanBal) AS CurrentLoanBalance
FROM Loan_MasterReference
WHERE ISNULL(LMR_KeyIDLink,0) = 0
GROUP BY Ref_Code

UNION ALL

SELECT LMR_KeyIDLink ,
SUM(LMR_CurrentLoanBal) 
FROM Loan_MasterReference
WHERE ISNULL(LMR_KeyIDLink,0) <> 0
GROUP BY LMR_KeyIDLink
)
group by parentID
ORDER BY ParentID
 
Forgot the correlation name for the derived table

Code:
select parentId,sum(CurrentLoanBalance)
from (
SELECT Ref_Code AS ParentID,
SUM(LMR_CurrentLoanBal) AS CurrentLoanBalance
FROM Loan_MasterReference
WHERE ISNULL(LMR_KeyIDLink,0) = 0
GROUP BY Ref_Code

UNION ALL

SELECT LMR_KeyIDLink ,
SUM(LMR_CurrentLoanBal)
FROM Loan_MasterReference
WHERE ISNULL(LMR_KeyIDLink,0) <> 0
GROUP BY LMR_KeyIDLink
) as dt
group by parentID
ORDER BY ParentID
 
for what it's worth, you don't need the ISNULL in there.

Code:
WHERE LMR_KeyIDLink <> 0

is exactly the same.

-------------------------------------
A sacrifice is harder when no one knows you've made it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top