简体   繁体   中英

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?

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?

lets say you have a table with the following columns : id timestamp amount

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. Grouping by this value and using the SUM() aggregate function will get you totals for each day.

DAYOFWEEK() returns a numeric value from a date representing the day of the week (1=Sunday, etc.). Grouping by this value and using the AVG() aggregate function will get you the average total for each weekday.

How to handle the results in PHP will depend on your specific needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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