gpt4 book ai didi

php - 如何在 php/mysql 中对时间间隔进行分组并根据这些时间组获取统计信息?

转载 作者:可可西里 更新时间:2023-11-01 07:05:28 24 4
gpt4 key购买 nike

我是 php 新手,我对时间/日期操作有疑问。

我需要对某个商店的日/月/年访问量进行统计。有一个带有表“statistics”和 fields: "statistic_id" ( integer, primary key ) , "visitors" ( integer ), and "dateAndTime" ( timestamp ) 的 mysql 数据库.我有一个表单,用户可以在其中输入来店的访客数量,然后使用 now() 函数将该数字连同时间和日期插入到数据库中。

所以基本上我的数据库看起来像:

statistic_id , visitors , timeAndDate <br />
1............, 3........., 2012-09-29 14:45:02 <br />
2............, 5........., 2012-09-29 14:46:31 <br />
3............, 2........., 2012-09-29 18:48:11 ...etc.

我需要做的是汇总并显示特定时间间隔内的所有访问者。 09h-12h ; 12h-15h ; 15h-18h ; 18h-21h .所以我需要在表格中显示所有这些间隔和每个间隔的访问者数量。问题是我不知道如何提取这些时间间隔,然后获取它们的访问者总和。我正在尝试我所知道的和我能找到的一切,但没有成功。此外,我还必须获得每月和每年的统计数据,那么我怎样才能获得所有 12 months来自这个timeAndDate列,然后是 sum all visitors for each month

有谁知道如何做到这一点,并愿意详细解释一下吗?谢谢

最佳答案

在 09:00 到 12:00 之间吸引访客

SELECT
SUM(`visitors`)

FROM
`my_table`

WHERE
HOUR(`timeAndDate`) BETWEEN 9 AND 12

按月获取访客

SELECT
MONTH(`timeAndDate`),
SUM(`visitors`)

FROM
`my_table`

GROUP BY
MONTH(`timeAndDate`)

按年获取访客

SELECT
YEAR(`timeAndDate`),
SUM(`visitors`)

FROM
`my_table`

GROUP BY
YEAR(`timeAndDate`)

在表格中输出月份的简单 PHP 示例

<?php

// Connect to database
$db = mysqli_connect('localhost', 'root', 'root', 'test') or die('Could not connect to database');

// Prepare sql question
$sql = "SELECT
MONTHNAME(`timeAndDate`) AS `month`,
SUM(`visitors`) AS `visitors`

FROM
`test`

GROUP BY
MONTH(`timeAndDate`)";

// Query the database
$result = mysqli_query($db, $sql);

// Begin table
print '<table><thead><tr><th>Month</th><th>Visitors</th></tr></thead><tbody>';

// Loop result
while($row = mysqli_fetch_assoc($result)) {
print "<tr><td>{$row['month']}</td><td>{$row['visitors']}</td></tr>";
}

// End table
print '</tbody></table>';

?>

关于php - 如何在 php/mysql 中对时间间隔进行分组并根据这些时间组获取统计信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12691660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com