Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL PHP group by day and total for each day

I have a table in a mysql database with 3 columns: id, value and tstamp. My tstamp column is in TIMESTAMP format, ie: 2011-01-21 08:32:22

What i hope to achieve is use PHP to display a break down of a total for each day. I cant think of a way to query the table, in pseudo code: select * from table group by day(part of tstamp) and add all numbers together from the value column for each day"

Is this going to be possible?

Thanks alot

EDIT:

I have this query in combo with the accepted answer's code:

$sql = "select date(tstamp), sum(".$column.") from mash group by date(tstamp)";
           $result = mysql_query($sql);
                while($row = mysql_fetch_array($result)){
                      $strXML .= "<set name='".date("G:i:s", strtotime($row["date"])).  "' value='".$row["sum"]."' color='AFD8F8' />";
                }

How do i access the array values in $row correctly?

like image 759
benhowdle89 Avatar asked Jan 21 '11 14:01

benhowdle89


2 Answers

If you want MySQL to return you the value you are looking for in ONE QUERY you can use:

select date(tstamp), sum(value)
  from your_table
 group by date(tstamp);
like image 163
Pablo Santa Cruz Avatar answered Oct 21 '22 19:10

Pablo Santa Cruz


How about using this

DATE_FORMAT(datestamp , '%Y') as year //for grouping over year
DATE_FORMAT(datestamp , '%Y-%m') as month //for grouping over month
DATE_FORMAT(datestamp , '%Y-%m-%d') as day //for grouping over day
like image 33
Eiad Avatar answered Oct 21 '22 17:10

Eiad