简体   繁体   English

来自php时间戳的平均每日金额

[英]average daily amount from timestamps in php

I have a mysql database with 2 values: a timestamp, and an amount How would I go about calculating an average for, say, every wednesday? 我有一个带有2个值的mysql数据库:时间戳记和数量我将如何计算每个星期三的平均值?

I would first have to see how many unique wednesdays are mentioned, then see how much the total value is for each specific wednesday (there can be multiple entries for one day, but the time of day is not relevant) Then I would have to add up all those values, and devide them by the amount of wednesdays. 我首先必须查看提到了多少个唯一的星期三,然后查看每个特定星期三的总价值是多少(一天中可以有多个条目,但是一天中的时间无关紧要),那么我必须添加总结所有这些价值,并以星期三的数量来表示。

I know this is oddly specific, that's why I probably haven't found anything about it. 我知道这很奇怪,这就是为什么我可能对此一无所获的原因。 How would I go about doing this in PHP? 我将如何在PHP中执行此操作?

lets say you have a table with the following columns : id timestamp amount 假设您有一个包含以下列的表格:id时间戳记量

You have to select all the rows from the table and put them in array. 您必须从表中选择所有行并将其放入数组。 Once it's done go trough the array 完成后,通过数组

<?php
$total = 0;
$bingo = 0;
foreach($a as $i)
{
    if(date( "l" ,$i["timestamp"]) == "Wednesday")
    {
        $bingo++;
        $total += $i["amount"];
    }
}
$avg = $total/$bingo;

?>

You could use a query like this to get daily averages for each weekday. 您可以使用这样的查询来获取每个工作日的每日平均值。

SELECT DAYOFWEEK(date_only), AVG(total) FROM (
    /*The subquery will return total amounts for each distinct day
      regardless of how many records there are for each day. */ 
    SELECT
        DATE(your_table.timestamp_column) as date_only, 
        SUM(your_table.amount_column) as total 
    FROM your_table 
    GROUP BY DATE(your_table.timestamp_column)) as daily_totals
GROUP BY DAYOFWEEK(date_only);

DATE() will take only the date part from the timestamp. DATE()将仅使用时间戳中的日期部分。 Grouping by this value and using the SUM() aggregate function will get you totals for each day. 按此值分组并使用SUM()聚合函数将获得每天的总计。

DAYOFWEEK() returns a numeric value from a date representing the day of the week (1=Sunday, etc.). DAYOFWEEK()从代表星期几的日期返回一个数字值(1 =星期日等)。 Grouping by this value and using the AVG() aggregate function will get you the average total for each weekday. 按此值分组并使用AVG()聚合函数将为您提供每个工作日的平均总数。

How to handle the results in PHP will depend on your specific needs. 如何在PHP中处理结果取决于您的特定需求。

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

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