简体   繁体   中英

Getting and comparing averages from MySQL with PHP

I want to be able to contrast "last weeks" data against "this weeks" data and get the percent change. (ie +1.2% or -.5%)

Here's an example of the MySQL table:

Date | Happy | Sad | Angry | Fearful
2016-04-01 | 2 | 1 | 3 | 0
2016-04-02 | 3 | 1 | 3 | 1
2016-04-03 | 0 | 4 | 1 | 2
2016-04-04 | 1 | 3 | 2 | 1

So pretending that there are at least 14 rows here how would I go about getting the average of the first 7 days, the average of the previous 7 days, and then creating the comparison that shows the percentage difference?

I can get the most recent 7 days averages with the code below, but when I try and repeat it and change the offset it fails:

    SELECT AVG(happy), AVG(sad), AVG(angry), AVG(fearful)
      FROM table_name
      LIMIT 0, 7

Use subqueries to calculate the averages for each week, using date ranges, and join them.

SELECT curWeek.happy AS curHappy, curWeek.sad AS curSad, curWeek.angry AS curAngry, curWeek.fearful AS curFearful,
       prevWeek.happy AS prevHappy, prevWeek.sad AS prevSad, prevWeek.angry AS prevAngry, prevWeek.fearful AS prevFearful,
       100*(curWeek.happy - prevWeek.happy)/prevWeek.happy AS happyChange,
       100*(curWeek.sad - prevWeek.sad)/prevWeek.sad AS sadChange,
       100*(curWeek.angry - prevWeek.angry)/prevWeek.angry AS angryChange,
       100*(curWeek.fearful - prevWeek.fearful)/prevWeek.fearful AS fearfulChange
FROM (SELECT AVG(happy) AS happy, AVG(sad) AS sd, AVG(angry) AS angry, AVG(fearful) AS fearful
      FROM tablename
      WHERE date > NOW() - INTERVAL 1 WEEK) AS curWeek
JOIN (SELECT AVG(happy) AS happy, AVG(sad) AS sd, AVG(angry) AS angry, AVG(fearful) AS fearful
      FROM tablename
      WHERE date BETWEEN NOW() - INTERVAL 2 WEEK AND NOW() - INTERVAL 1 WEEK) AS prevWeek

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