Search code examples
mysqlsqlmonthcalendar

How to discover the sum of each day of a month in MySQL?


Lets suppose we have a table (for example sales) with three fields id (int, primary), price (double), date (datetime).

How can we get the sum of the price attribute to each day of the current month?

And to the last month?

I need a return with something similar too:

February

01        02        03        04        ...        30
101.1     233.43    1232.42  3232.21             121.23

April

01        02        03        04        ...        30        31
11.1     23.43      122.42   332.21              121.23    2323.32

How could we perform this?

Please give me a SQL as example.

I thinking to write a method to discover the number of days of the month and than create the SQL iteratively, but I think this isn't the best way.


Solution

  • Collecting all ideas (thx @MarcB, @Stephan, @GordonLinoff) the SQL bellows is what I'm looking for:

    February

    SELECT
        SUM(price) AS daySum
    FROM
        sales
    WHERE
        date BETWEEN DATE_FORMAT(NOW() - INTERVAL 2 MONTH,'%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 2 MONTH),'%Y-%m-%d 23:59:59')
    GROUP BY
        YEAR(date),
        MONTH(date),
        DAY(date)
    

    April (we are currently at April month)

    SELECT
        SUM(price) AS daySum
    FROM
        sales
    WHERE
        date BETWEEN DATE_FORMAT(NOW(),'%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(NOW()),'%Y-%m-%d 23:59:59')
    GROUP BY
        YEAR(date),
        MONTH(date),
        DAY(date)
    

    Thx a lot.