Reputation: 1276
Here is my problem:
I got a table like this one:
Table Log
int id;
int time;
timestamp DATE;
int sid (FK to table Site);
and a table Site:
Table Site;
int id;
varchar title;
In my log table, a site can be present 0 or N times, I need to get the sum of time for each site.
This request is done and seems to work, now I need to get the site title and the average of the sum time for a specific period in my logs.
Here is my query:
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;
But the average seems to not be working in this case, the value i'm getting is a the sum i've computed in my subquery, any help?
EDIT:
Here is a data sample:
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
What I need now is, an average on the time sum on a period (let's say 2012-11-13 to 2012-11-14 for this example), so as for the expected datas:
Site, avg time sum
Site A, 8500
Site B, 5750
Upvotes: 0
Views: 6073
Reputation: 1276
I solved my problem, found the good way to write the query (thanks to @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
Upvotes: 6
Reputation: 1888
try this
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;
Upvotes: -1