tags:

views:

123

answers:

3

Hi, I have an SQL table like this : sales(product,timestamp) I want to display a chart using Open Flash Chart but i don't know how to get the total sales per hour within the last 12 hours. ( the timestamp column is the sale date )

By example i will end up with an array like this : array(12,5,8,6,10,35,7,23,4,5,2,16) every number is the total sales in each hour.

Note: i want to use php or only mysql for this.

Thanks

+2  A: 

The SQL is

SELECT HOUR(timestamp), COUNT(product)
FROM sales
ORDER BY HOUR(timestamp)

Loop over the result to get it into an array.

EDIT: Applying requested where condition for unix timestamp

SELECT HOUR(timestamp), COUNT(product)
FROM sales
WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(NOW(),INTERVAL 12 HOUR))
ORDER BY HOUR(timestamp)
Unreason
+1 for the sql only version.
zaf
Thanks man, that's clean
David
I forgot, i want it to only get the latest 12 hours :D i think Keith's Date_sub doesn't work for me
David
Updated the answer, for future reference http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_unix-timestamp
Unreason
A: 

Some pseudo code:

foreach timestamp
  use date('G',timestamp) to get hour
  increment array value using the hour as key

Something along those lines. Watch out for timezones.

zaf
+2  A: 
SELECT HOUR(timestamp),COUNT(*)
FROM sales
WHERE timestamp >= DATE_SUB(NOW(),INTERVAL 12 HOUR)
GROUP BY HOUR(timestamp)
Keith
+1 for reading the question in detail :)
Unreason
The timestamp >= DATE_SUB(NOW(),INTERVAL 12 HOUR) part doesn't work :( maybe because it's a Unix time stamp?
David