[SOLVED] MySQL cumulative total by month


I’m trying to sum totalSales based on the month selected, i.e if March is selected then sum totalSales from January to March

Sales table

id month year totalSales
1 January 2019 150000
2 February 2019 120000
3 March 2019 80000
4 April 2019 200000
5 May 2019 400000


This worked

SELECT * FROM (SELECT month, year,
    SUM(totalSales) OVER (PARTITION BY year ORDER BY FIELD(month, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')) AS totalSales
        ) temp
    WHERE year=2021 AND month='May'

Answered By – Matt

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *