Home > Enterprise >  getting sum for each month for several months in a year in sql
getting sum for each month for several months in a year in sql

Time:02-18

I have the following table
image of database in use
i want to get the following kind of results

jan 12500
feb 16500
mar 4500
apr 6500

the query should return a total for each month for desired months. i know how to do this..

    $sql = "SELECT SUM(cost) as january FROM earnings WHERE month= 1 and year= '$2022" ;

to get the sum for a given month but I cant find anything on how to get multiple months at once. am still new to this

CodePudding user response:

SELECT 
   SUM(cost) as cost,
   month 
FROM earnings 
WHERE year = :year  
GROUP BY month 

Sum all entries of cost, per month (GROUP BY) found in year (:year) Each ROW will have a column cost and month.

If you want to "further" filter the months you can apply another AND clause

AND (month >= 1 OR month <= 6) for January to June

Useful Source: https://www.mysqltutorial.org/mysql-group-by.aspx

  • Related