MySQL平均值总和

时间:2012-11-15 10:51:22

标签: mysql sum average

这是我的问题:

我有一张像这样的桌子:

 Table Log
 int id;
 int time;
 timestamp DATE;
 int sid (FK to table Site);

和表格网站:

 Table Site;
 int id;
 varchar title;

在我的日志表中,一个站点可以存在0或N次,我需要获得每个站点的时间总和。

此请求已完成且似乎有效,现在我需要获取网站标题以及日志中特定时间段的平均时间。

这是我的问题:

SELECT site, AVG(sumtime)
FROM (
    SELECT Site.TITLE as site, SUM(time) as sumtime FROM Log
    INNER JOIN sites ON Site.ID = Log.sid
    WHERE Log.DATE between '2012-11-13' AND '2012-11-15'
    GROUP BY Site.TITLE
) AS t1
GROUP BY t1.site;

但是在这种情况下,平均值似乎不起作用,我得到的值是我在子查询中计算的总和,任何帮助?

编辑:

以下是数据样本:

Site
1 SiteA
2 SiteB

Log
1 2500 "2012-11-14 07:00:01" 1
2 3500 "2012-11-14 07:10:01" 1
3 4500 "2012-11-14 07:12:01" 1
4 6500 "2012-11-13 10:10:01" 1
5 2500 "2012-11-14 08:00:01" 2
6 3500 "2012-11-14 10:10:01" 2
7 5500 "2012-11-13 12:10:01" 2

我现在需要的是,一段时间内的平均时间总和(比如2012-11-13到2012-11-14这个例子),以及预期的数据:

Site, avg time sum
Site A, 8500
Site B, 5750

2 个答案:

答案 0 :(得分:6)

我解决了我的问题,找到了编写查询的好方法(感谢@tombom):

SELECT t1.site, AVG(sumtime)
FROM (
    SELECT Site.TITLE as site, SUM(time) as sumtime FROM Log
    INNER JOIN Site ON Site.ID = Log.sid
    AND Log.DATE between '2012-11-14' AND '2012-11-15'
    GROUP BY site, DATE(Log.DATE)
) AS t1
group by t1.site

答案 1 :(得分:-1)

试试这个

SELECT t1.site, AVG(t1.sumtime)
FROM (
SELECT Site.TITLE as site, SUM(time) as sumtime FROM Log
INNER JOIN sites ON Site.ID = Log.sid
WHERE Log.DATE between '2012-11-13' AND '2012-11-15'
GROUP BY time
) AS t1
GROUP BY t1.site;