Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQl query to sum-up amounts by month/year

Tags:

sql-server

I have a table "TABLE" like this:

Date(datatime)
Paid(int)

I have multiple "Paid" amounts per month. I would like to sum up the Paid amount per month/year.

So far this is what I tried but I get errors in EXTRACT and in MONTH and however I am far to get it done with the years.

SELECT 
     EXTRACT(MONTH FROM Period) AS reference_month
     , SUM(Paid) AS monthly_payments 
FROM Paid 
GROUP BY EXTRACT(MONTH FROM Period) 
ORDER BY EXTRACT(MONTH FROM Period)

I am not really handy at this and I would really appreciate some help.

like image 427
Nullbyte Avatar asked Jan 07 '14 14:01

Nullbyte


2 Answers

select year(date) as y, month(date) as m, sum(paid) as p
from table
group by year(date), month(date)
like image 63
davek Avatar answered Nov 09 '22 19:11

davek


SELECT YEAR([Date]) AS [Year], MONTH([Date]) AS [Month], SUM(Paid) AS Total
FROM TABLE_NAME
GROUP BY YEAR([Date]), MONTH([Date]) 

You need to use square brackets around your objects name [] when you have named your object with sql server key words.

like image 32
M.Ali Avatar answered Nov 09 '22 17:11

M.Ali