1

How to use sum function in joins in sql server 2008?

SELECT SUM(d.TranTypeAmt),
       h.LnNo,
       h.LoanRcptAmt,
       d.Trantype,
       d.TranTypeAmt
FROM   LGen_LnInstClln_h h
       RIGHT OUTER JOIN LGen_LnInstClln_d d
         ON h.PK_Id = d.InstCllnHdr_FK
WHERE  h.LnNo = '40009' 
2
  • What's the problem with the above SQL? Commented Jul 18, 2012 at 11:08
  • 1
    Your WHERE clause turns the right outer join into an inner join. Commented Jul 18, 2012 at 11:10

2 Answers 2

2

When using an aggregate function, such as SUM() you need to either use aggregate functions on the rest of the data items, or group by them.

select  SUM(d.TranTypeAmt), h.LnNo,h.LoanRcptAmt,d.Trantype,d.TranTypeAmt
from LGen_LnInstClln_h h 
right outer join LGen_LnInstClln_d d on h.PK_Id=d.InstCllnHdr_FK  
where h.LnNo='40009'
GROUP BY h.LnNo,h.LoanRcptAmt,d.Trantype,d.TranTypeAmt
Sign up to request clarification or add additional context in comments.

3 Comments

The question says nothing about the cardinality of the relation between the tables. If one PK_Id matches multiple d.InstCllnHdr_FK, then the SUM function will sum up those multiple matches. Is this what kalaivanan wants?
by using the above query following error is displaying olumn 'LGen_LnInstClln_h.LnRcptNo' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
@kalaivanan: h.LnRcptNo is not part of the SELECT list in this query. I think you accidentally changed it. What happens when you execute the query as it is, without changing anything?
0

You should have a group by clause when using aggregate function, with other columns in the select list.

so here you should add

group by 
h.LnNo,
       h.LoanRcptAmt,
       d.Trantype,
       d.TranTypeAmt

at the end of the query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.