聚合函数

时间:2011-11-16 11:18:26

标签: mysql

我有一个包含以下信息的表

date             sales
2011-02-13        1
2011-02-13        3
2011-02-13        2
2011-02-14        1
2011-02-14        5
2011-02-14        8
2011-02-15        2
etc ...

我怎么知道这段时间的平均金额是多少? 例如,我想得到像这样的结果: 2011-02-11 - 2011-02-15期间的销售量为每天2,4笔。

2 个答案:

答案 0 :(得分:1)

select avg(sales) from table where date <= x and date >= y

你的x和y是日期,例如。

 select avg(sales) from table where date <= '2011-02-15' and date >= '2011-02-11'

答案 1 :(得分:1)

如果`date`属于DATE数据类型:

SELECT SUM(sales) / (1 + DATEDIFF('2011-02-15', '2011-02-11'))
       AS AverageSalesPerDay
FROM TableX 
WHERE `date` BETWEEN '2011-02-11' 
                 AND '2011-02-15'

如果是DATETIMETIMESTAMP

SELECT SUM(sales) / (DATEDIFF('2011-02-16', '2011-02-11'))
       AS AverageSalesPerDay
FROM TableX 
WHERE `date` >= '2011-02-11' 
  AND `date` <  '2011-02-16'