简体   繁体   English

按天获取统计信息-datetime列-MySQL / PHP

[英]Get statistics by day - datetime column - mysql/php

I have an issue that I can't solve by myself. 我有一个我自己无法解决的问题。 The best thing would be if it's possible to do it directly from mysql but if not, calculating from php is also good. 最好的事情是,如果可以直接从mysql进行操作,但如果不能,则从php计算也可以。

I have a table that has 3 columns: id, time, value 我有一个包含3列的表:id,时间,值

Now the time value is datetime (example: 2012-11-03 00:13:12) 现在时间值为datetime(例如:2012-11-03 00:13:12)

I want to create statistics from the last 7 days. 我想创建最近7天的统计信息。 Let's say I have 7 rows and today is 2012-12-20. 假设我有7行,今天是2012-12-20。

Here are the rows: datetime value 以下是这些行:datetime值
2012-12-20 00:12:12 2 2012-12-20 00:12:12 2
2012-12-20 04:06:15 4 2012-12-20 04:06:15 4
2012-12-20 03:12:14 5 2012-12-20 03:12:14 5
2012-12-18 03:12:14 7 2012-12-18 03:12:14 7
2012-12-16 12:12:14 3 2012-12-16 12:12:14 3
2012-12-16 14:23:34 2 2012-12-16 14:23:34 2
2012-12-15 14:23:34 9 2012-12-15 14:23:34 9

If I want to get the last 7 days report, it would be this: 如果我想获取最近7天的报告,那就是:

2012-12-14 -> value =0 2012-12-14->值= 0
2012-12-15 -> value =9 2012-12-15->值= 9

2012-12-16 -> value =5 2012-12-16->值= 5

2012-12-17 -> value =0 2012-12-17->值= 0

2012-12-18 -> value =7 2012-12-18->值= 7
2012-12-19 -> value =0 2012-12-19->值= 0

2012-12-20 -> value =11 2012-12-20->值= 11

Currently I have this (extract last 7 day records): 目前我有这个(提取最近7天的记录):

$date=date("Y-m-d");
$date=date ("Y-m-d", strtotime ( '-7 day' . $date ) );  
$qry="select value,date from mytable where date>'$date'";
$res=mysql_query($qry) or die("Couldn't select Information : ".mysql_error());
while($row=mysql_fetch_array($res))
    {
        echo $row["value"];
    }

I hope somebody can help with advice. 我希望有人可以提供建议。 Thanks in advance! 提前致谢! Vlad 弗拉德

This should be relatively easy to solve using just MySQL. 仅使用MySQL,这应该相对容易解决。 This is very similar to this question: MySQL Query GROUP BY day / month / year 这与以下问题非常相似: MySQL Query GROUP BY按日/月/年

You need to change your query so it gets all the records for a given week. 您需要更改查询,以便获取给定一周的所有记录。

SELECT DAY(date) , SUM(value)
FROM mytable
WHERE WEEK(date) = WEEK(NOW())
GROUP BY DAY(date)

Its also very easy to change how you group the numbers, for example by month using GROUP BY MONTH(date) . 更改数字分组方式也非常容易,例如使用GROUP BY MONTH(date)按月进行分组。 You could also make the MySQL display the day name as a field by doing SELECT DAYNAME(date) For more details on what functions are available check out the MySQL User Guide on Date and Time functions . 您也可以通过执行SELECT DAYNAME(date)来使MySQL将日期名称显示为字段。有关可用功能的更多详细信息,请查阅MySQL用户指南中的Date and Time函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM