Question

I have a mysql db which I use to return amounts of orders by hour in a specific day. I use this SELECT statement for that.

select
   hour(datains),sum(valore)
from
   ordini  
where (stato=10 or stato = 1  ) and DATE(datains) = DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 0 DAY)  
group by hour(datains)
order by
   id DESC

It returns:

+--------------+---------------+
| hour datains |    valore     |
|      12      |      34       |
|      11      |      56       |
|      10      |     134       |
+-------------------------------

Now I need to have columns for a certain number of days, like this.

+--------------+---------------+--------------+--------------+
| hour datains |    01-01-2014 |   02-01-2014 |   03-01-2014 |            
|      12      |      34       |     34       |     77       |
|      11      |      56       |     0        |    128       |
|      10      |     134       |     66       |     12       |
+------------------------------+-----------------------------+

Is this possible?

Was it helpful?

Solution

It seems you have a table ordini with columns datains, valore, and stato.

Perhaps you can try this query to generate hour-by-hour aggregates for a three days' worth of recent sales, but not including today.

SELECT DATE_FORMAT(datains, '%Y-%m-%d %H:00') AS hour,
       SUM(valore) AS valore
  FROM ordini
 WHERE (stato = 1 OR stato = 10)
   AND datains >= CURRENT_DATE() - INTERVAL 3 DAY
   AND datains <  CURRENT_DATE
 GROUP BY DATE_FORMAT(datains, '%Y-%m-%d %H:00')
 ORDER BY DATE_FORMAT(datains, '%Y-%m-%d %H:00')

This will give you a result set with one row for each hour of the three days, for example:

2014-01-01 10:00       456
2014-01-01 11:00       123
2014-01-02 10:00        28
2014-01-02 11:00       350
2014-01-02 12:00       100
2014-01-02 13:00        17
2014-01-03 10:00       321
2014-01-03 11:00       432
2014-01-03 12:00        88
2014-01-03 13:00        12

That's the data summary you have requested, but formatted row-by-row. Your next step is to figure out an appropriate technique to pivot that result set, formatting it so some rows become columns.

It happens that I have just written a post on this very topic. It is here: http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top