我试图得到每个月所有周的平均值。如何在mysql中实现这一点?以下是我所拥有的,也是我所需要的:
SELECT
date_part(year, date_of_act) AS CALENDAR_YEAR,
date_part(week, date_of_act) AS CALENDAR_WEEK_OF_YEAR,
(num_active_divs / total_num_divs) AS "Weekly average for each year of week"
FROM
Infotable
GROUP BY calendar_year, calendar_week_of_year
ORDER BY calendar_year, calendar_week_of_year
What I have: What I have: What I have:
Calendar_Year Days of the year Calendar_Week_of_year Weekly average for each year of week
2018, Jan 01 - Jan 07, 1, 0.266855
2018, Jan 08 - Jan 14, 2, 0.297223
2018, Jan 15 - Jan 21, 3, 0.308583
2018, Jan 22 - Jan 28, 4, 0.309994
2018, Jan 29 - Feb 04, 5, 0.317419
2018, Feb 05 - Feb 11, 6, 0.316454
2018, Feb 12 - Feb 18, 7, 0.313929
2018, Feb 19 - Feb 25, 8, 0.315489
2018, Feb 26 - Mar 04, 9, 0.3218
2018, Mar 05 - Mar 11, 10, 0.308509
2018, Mar 12 - Mar 18, 11, 0.302866
2018, Mar 19 - Mar 25, 12, 0.31586
What I need: What I need: What I need: What I need:
Calendar_Year Calendar_Week_of_year Weekly average for each year of week Calendar_Month_of_year Week_of_month Average for all weeks in that month
2018, Jan 01 - Jan 07, 1, 0.266855, 1, 1
2018, Jan 08 - Jan 14, 2, 0.297223, 1, 2
2018, Jan 15 - Jan 21, 3, 0.308583, 1, 3
2018, Jan 22 - Jan 28, 4, 0.309994, 1, 4, (0.266855+0.297223+0.308583+0.309994)/4
2018, Jan 29 - Feb 04, 5, 0.317419, 2, 1
2018, Feb 05 - Feb 11, 6, 0.316454, 2, 2
2018, Feb 12 - Feb 18, 7, 0.313929, 2, 3
2018, Feb 19 - Feb 25, 8, 0.315489, 2, 4, (0.317419+0.316454+0.313929+0.315489)/4
2018, Feb 26 - Mar 04, 9, 0.32180, 3, 1
2018, Mar 05 - Mar 11, 10, 0.308509, 3, 2
2018, Mar 12 - Mar 18, 11, 0.302866, 3, 3
2018, Mar 19 - Mar 25, 12, 0.31586, 3, 4, (0.3218+0.308509+0.302866+0.31586)/4
1条答案
按热度按时间4sup72z81#
这里的一个选项是连接到一个子查询,该子查询查找每月平均值:
如果您使用的是mysql 8+,那么您可能可以使用
AVG
作为一个解析函数。在这种情况下,查询变得不那么简洁: