查询计算每个季度的平均值
Query to calculate average for each quarter
我是 MySQL 的新手,需要您的帮助来找出查询,以便计算每个季度的平均值。
我有一个名为 USretail92_21 的 table,看起来像这样(从 1992 年到 2021 年):
Date
Sales
1992-01-01
701.0
1992-02-01
658.0
1992-03-01
731.0
1992-04-01
816.0
1992-05-01
856.0
1992-06-01
853.0
1992-07-01
101.0
1992-08-01
558.0
1992-09-01
431.0
考虑日期格式 1992-01-01 表示 1992 年 1 月。现在我 运行 下面的查询来获取季度和月份:
select year(date) as Year,monthname(date)as Month, quarter(date) as Quarter, sales from USretail92_21 where kind="Men's clothing stores" order by 1
这给了我这个观点:
Year
Month
Quarter
Sales
1992
January
1
701.0
1992
February
1
658.0
1992
March
1
731.0
1992
April
2
816.0
1992
May
2
856.0
1992
June
2
853.0
现在我的问题是如何获得每季度的平均销售额并得到如下所示的输出:
Quarter
Year
AverageSales
1
1992
696 (average for Jan/Feb/March)
2
1992
841
最终,我想要一个图表,其中 Python 将销售额视为 Y 轴,将“Q1_92 至 Q4_21”视为 X 轴
您需要使用 GROUP BY
来计算总和和平均值等聚合。
根据您的示例工作:
WITH SalesPerMonth AS (
select year(date) as Year,
monthname(date)as Month,
quarter(date) as Quarter,
sales from USretail92_21
where kind="Men's clothing stores"
)
SELECT Quarter, Year, AVG(Sales) AS AverageSales
FROM SalesPerMonth
GROUP BY Quarter, Year
或者一次性完成:
select year(date) as Year,
quarter(date) as Quarter,
AVG(sales) AverageSales
from USretail92_21
where kind="Men's clothing stores"
group by year(date),
quarter(date)
我是 MySQL 的新手,需要您的帮助来找出查询,以便计算每个季度的平均值。 我有一个名为 USretail92_21 的 table,看起来像这样(从 1992 年到 2021 年):
Date | Sales |
---|---|
1992-01-01 | 701.0 |
1992-02-01 | 658.0 |
1992-03-01 | 731.0 |
1992-04-01 | 816.0 |
1992-05-01 | 856.0 |
1992-06-01 | 853.0 |
1992-07-01 | 101.0 |
1992-08-01 | 558.0 |
1992-09-01 | 431.0 |
考虑日期格式 1992-01-01 表示 1992 年 1 月。现在我 运行 下面的查询来获取季度和月份:
select year(date) as Year,monthname(date)as Month, quarter(date) as Quarter, sales from USretail92_21 where kind="Men's clothing stores" order by 1
这给了我这个观点:
Year | Month | Quarter | Sales |
---|---|---|---|
1992 | January | 1 | 701.0 |
1992 | February | 1 | 658.0 |
1992 | March | 1 | 731.0 |
1992 | April | 2 | 816.0 |
1992 | May | 2 | 856.0 |
1992 | June | 2 | 853.0 |
现在我的问题是如何获得每季度的平均销售额并得到如下所示的输出:
Quarter | Year | AverageSales |
---|---|---|
1 | 1992 | 696 (average for Jan/Feb/March) |
2 | 1992 | 841 |
最终,我想要一个图表,其中 Python 将销售额视为 Y 轴,将“Q1_92 至 Q4_21”视为 X 轴
您需要使用 GROUP BY
来计算总和和平均值等聚合。
根据您的示例工作:
WITH SalesPerMonth AS (
select year(date) as Year,
monthname(date)as Month,
quarter(date) as Quarter,
sales from USretail92_21
where kind="Men's clothing stores"
)
SELECT Quarter, Year, AVG(Sales) AS AverageSales
FROM SalesPerMonth
GROUP BY Quarter, Year
或者一次性完成:
select year(date) as Year,
quarter(date) as Quarter,
AVG(sales) AverageSales
from USretail92_21
where kind="Men's clothing stores"
group by year(date),
quarter(date)