Nathan
Nathan

Reputation: 78439

SQL group summing

Okay, say that I have two columns, Person and Donation. With, for example, these as rows:

+++++++++++++++
Fred | $1000 
Fred |  $500 
Bob  | $1000
Bob  | $7000
Sally|  $500
Joe  |  $100  
+++++++++++++++

How could I get it to display the following?

+++++++++++++++
Fred | $1500
Bob  | $8000
Sally|  $500
Joe  |  $100  
+++++++++++++++

In other words, how could I group together all the donations under a certain person, and sum them up? What would be an example query that would accomplish this? (If at all possible, in a general way, that does not involve individually naming the people in the select/sum clause)

Thanks!

Upvotes: 1

Views: 272

Answers (3)

mayur jani
mayur jani

Reputation: 1

You can use the following query for this:

SELECT Name "Name", SUM(Donation) "Donation" FROM Donations GROUP BY Name

Upvotes: 0

刘伟科
刘伟科

Reputation: 432

select sum(a.donation),a.person from a_table as a group by a.person;

a_table is your table;

Upvotes: 2

akatakritos
akatakritos

Reputation: 9858

When you use a GROUP BY clause with an aggregate function (like SUM) the aggregate is calculated for each group.

SELECT Name, SUM(Donation) FROM Donations GROUP BY Name

If you want to get more specific results, like those people with total donations more than $500, introduce a HAVING clause. This is sort of like a WHERE for aggregate results:

SELECT Name, SUM(Donation) FROM Donations GROUP BY Name 
    HAVING SUM(Donation) > 500

SQL Fiddle: http://sqlfiddle.com/#!2/2de84/1/0

Upvotes: 6

Related Questions