Need help on SQL Query

ItemID  ItemName    ItemPrice
101      McDonald's    90

UID  ItemID   UserId  ContributedAmount  
1     101       U001           50
2     101       U002           40
3     101       U003            0
4     101       U004            0

I have two tables shown as above , 4 Persons go to a restaurant and the total bill was 90$
Person1 pays 50$ and Person2 pays 40$ and other 2 persons didnt pay at all.
The paid amount should be shared equally among 4, Now i need a query to find out who needs to pay
to whom of how many amount ($'s) ?  Help would be appreciated

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Try this if it works for you.
select UID, test.ItemID,UserID,ContributedAmount, convert(decimal,Total)/convert(decimal,TotalCount) EachContri
, ContributedAmount - (convert(decimal,Total)/convert(decimal,TotalCount)) pendingAmount
from test inner join 
(select itemid,SUM(ContributedAmount) Total,COUNT(*) TotalCount  from test group by itemid) t
on test.itemid = t.itemid

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dprasannainAuthor Commented:
Had to do some modification in the query make it work as i wanted
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.