Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

You actually want to do a pivot:

select year(date), month(date),
       sum(case when day(date) = 1 then price end) as price_01,
       sum(case when day(date) = 2 then price end) as price_02,
       . . .
       sum(case when day(date) = 31 then price end) as price_31
from sales
group by month(date), year(date)

Then add a where clause for the dates that you want. Something like:

where month(date) = month(now())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top