I have this database table ‘market’
id market_id shows clicks event data
1 158 1000 300 on 2012-03-01
2 158 1500 600 off 2012-03-14
3 158 1500 600 on 2012-03-14
4 158 2500 700 off 2012-03-20
I want to select it and get array like this:
$array = array (
array('from 2012-03-01 to 2012-03-14' => array('shows' => 500, 'clicks' => 300)
array('from 2012-03-14 to 2012-03-20' => array('shows' => 1000, 'clicks' => 100)
How to do that? Have I do that in Mysql or have I do that in php?
edit:
‘shows’ in array calculates like that 1500 – 1000, 1500 is from table where ‘event’ is off and 1000 is from table where ‘event’ is on, click’s calculate same.
Caveat: I can’t really work out what your intention is and hence there may be much better solutions that this but…
Here’s a query that works on your sample data.
To explain a little bit: the query joins the table onto it self to find all pairs of rows where one represents an “off” event that is later than an “on” event. This picks up all pairs (even 2012-03-20 ‘off’ and 2012-03-01 ‘on’) so then we do a LEFT JOIN again to check there are no other ‘on’ events between the ‘on’ row and the ‘off’ row.
btw, I think there’s an error in your sample results. The values for “shows” in your second result should be 1000.