Link to home
Start Free TrialLog in
Avatar of tommym121
tommym121Flag for Canada

asked on

SQL - How to sum up a column 'Balance' based on the first and last name of the records

I have a table

First|Last| Address|Bank Account|Balance
Tommy|Miller |1 Kingston St |123456|10.00
John      |Smith|12 rose St       |34567   | 20.00
John      |Smith|12 rose St       |91234   | 30.00
Tommy|Miller |1 Kingston St |23457   | 15.00

I am hopping I can do a Select that will give me such a result
Select First, Last, Sum(Balance) ......
Tommy|Miller |25.00
John      |Smith| 50.00

Basically I want to report  records of that has unique fullname (First + ' ' + Last)
I can use this below to get the unique records, but how can I modify to get the sum for each user.

with cte as
(
  select First, Last, Address ,
             ROW_NUMBER() OVER (PARTITION BY First, Last ORDER BY First, Last) RN
   from TestDuplicate.dbo.Contact
)
select First, Last, Address
from cte
where RN = 1
ASKER CERTIFIED SOLUTION
Avatar of MrHswede
MrHswede
Flag of Sweden 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
Avatar of tommym121

ASKER

Cenjoy100

When I add Address into the select statement

select First,Last, Address, sum(Balance) as totalbalance
from TestDuplicate.dbo.Contact
group by First,Last

I get an error when execute,  how can I avoid this error, if I need the Address in my result

Column 'TestDuplicate.dbo.Contact' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
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
SOLUTION
Avatar of Patrick Matthews
Patrick Matthews
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
Patrick,

Thanks for your suggestion.  I am working with a database from my supplier.  I was not given any schema.  But looking at it, it is not well structure.
Ah yes, the dreaded problem of "Somebody Else's Data".

:)
Thanks