MYSQL子查询从过去X天开始的平均数

时间:2017-03-15 21:35:29

标签: mysql sql

假设我有以下类型的表,名为item_sales:

Item, Sales Date, Num_Sold
--------------------------
item1, 2017-01-02, 500
item1, 2017-01-03, 350
item1, 2017-01-04, 450
item2, 2017-01-02, 750
item2, 2017-01-03, 1100
item2, 2017-01-04, 1000
item3, 2017-01-02, 200
item3, 2017-01-03, 100
item3, 2017-01-04, 100

等等。我知道如何按项目返回平均销售量。

select item, avg_sold 
 from 
 (
   select item, avg(num_sold) as avg_sold 
   from item_sales 
   group by item
 ) as avg_table 
where avg_sold > 200;

然后返回

item   avg_sold
------|-------
item1 | 433.00
item2 | 950.00

现在,我希望能够做的是返回相同的平均值,但回顾过去的X天,比如过去30或60天。我不知道该怎么做。

1 个答案:

答案 0 :(得分:4)

您的查询不需要子查询,只需要having子句:

select item, avg(num_sold) as avg_sold 
from item_sales 
group by item
having avg_sold > 200;

然后,您只需添加where

select item, avg(num_sold) as avg_sold 
from item_sales 
where sale_date >= date_sub(curdate(), interval 30 day)
group by item
having avg_sold > 200;