tags:

views:

23

answers:

2

Not a SQL guy, so i'm in a bind, so I'll keep this simple

+--------------+------------------------+
| RepaymentDay | MonthlyRepaymentAmount |
+--------------+------------------------+
|            3 |               0.214847 | 
|           26 |               0.219357 | 
|           24 |               0.224337 | 
|            5 |               0.224337 | 
|           18 |               0.224337 | 
|           28 |               0.214847 | 
|            1 |               0.224337 | 
|           28 |               0.327079 |
+--------------+------------------------+

I am looking for a query that would then give something like;

+--------------+------------------------+
| RepaymentDay | MonthlyRepaymentAmount |
+--------------+------------------------+
|            1 |               0.224337 | 
|            3 |               0.214847 | 
|            5 |               0.224337 | 
|           18 |               0.224337 | 
|           24 |               0.224337 | 
|           26 |               0.219357 | 
|           28 |               0.541926 | 
+--------------+------------------------+

I.e Where there are multiple records with the same value of 'RepaymentDay' , to sum those values of 'MonthlyRepaymentAmount'.

I could do it externally with perl or python, no issue, but I want to try and become more familiar with SQL. Any ideas?

+5  A: 
SELECT RepaymentDay, SUM(MonthlyRepaymentAmount) AS MonthlyRepaymentAmount
FROM YourTable
GROUP BY RepaymentDay
ORDER BY RepaymentDay
Martin Smith
I don't think you need the ORDER BY in MySQL - it is done automatically. +1 for fast answer though.
Mark Byers
@Mark - Thanks. Didn't know that about MySQL.
Martin Smith
@martin, thanks for the speedy reply, now if only the checkmark permissions were as speedy!
Andrew Bolster
@Martin Smith: It's a bizarre (but documented) feature in MySQL. If you *don't* want the sorting you have to add `ORDER BY NULL`. See http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html Leaving the ORDER BY is fine though - it doesn't cause a performance loss. Sorry this a bit off-topic for this question but I just thought you would be interested. :)
Mark Byers
+1  A: 

select RepaymentDay, sum(MonthlyRepaymentAmount) from table_name group by RepaymentDay;

Jeremy
Martin's is cleaner with the renaming of the group and the explicit ordering.
Jeremy