从表中逐日汇总值

时间:2015-05-14 12:24:38

标签: php mysql

我有一个收集数据的脚本,表格就是这个结构

 Date - Y-m-d H:i:s
 Name - Example
 Quantity - 1

Example
 ID - Date - Name - Quantity
 1 - 2015-05-13 16:33:09 - Test1 - 1
 2 - 2015-05-13 19:10:45 - Test2 - 3
 3 - 2015-05-13 22:01:39 - Test3 - 1
 4 - 2015-05-14 07:13:20 - Test4 - 1
 5 - 2015-05-14 09:29:37 - Test5 - 2

如何按日期在2015-05-13同一天添加数量,以此文本格式输出数据:5,3 ......

require_once 'config.php';

$mysqli = new mysqli($server, $db_user, $db_password, $database);

if ($mysqli->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, date, quantity FROM downloads";
$result = $mysqli->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["quantity"]. "<br>";
    }
} else {
    echo "0 results";
}
$mysqli->close();

2 个答案:

答案 0 :(得分:1)

使用此查询获取每个日期的数量总和

SELECT DATE(`Date`), SUM(quantity) FROM downloads GROUP BY DATE(`Date`)

它会按日期时间列Date的日期部分对结果进行分组,并为每个日期提供quality列的总和。

DATE功能说明:https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date

SUM函数说明:https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum

答案 1 :(得分:1)

您需要的查询是:

SELECT DATE(`date`) AS dateWhen, SUM(quantity) AS total
FROM downloads
GROUP BY dateWhen