2013-09-29 130 views
1

我试着计算每天每小时的平均帖子数,而且我必须在113个月内这样做。 Post表内有这个属性timePosted,DatePosted和Text。我还需要加入两个表格帖子和线程,因为我只想获取类别ID号3.MySQL:计算每天每小时的平均帖子数

到目前为止,这是我所做的查询。

select datePost as daytime, 
    HOUR(timePost) as thehour, 
    count(TEXT) as thecount 
    from post, thread 
    where date(post.datePost) BETWEEN '2010-05-01' AND '2010-05-31' 
    and post.threadID = thread.threadID 
    and thread.CatID = 3 
    group by datePost, thehour 

上述子查询返回我:

daytime  thehour thecount 
'2010-05-01', '0',  '3' 
'2010-05-01', '1',  '16' 
'2010-05-01', '2',  '2' 
'2010-05-01', '4',  '1' 
'2010-05-01', '7',  '1' 

我尝试做平均,但问题是,它返回我同样数量thecount。例如thecount是3,那么平均回报我3.00000

所以我试图让这个结局:

daytime  thehour thecount  Avg 
'2010-05-01', '0',  '3'   # 
'2010-05-01', '1',  '16'   # 
'2010-05-01', '2',  '2'   # 
'2010-05-01', '4',  '1'   # 
'2010-05-01', '7',  '1'   # 

回答

1

刚组用任何你需要

select month(timePost), day(timePost), hour(timePost),avg(the_count) 
from 
(
    select datePost as the_day, 
    timePost, 
    count(TEXT) as the_count 
    from post, thread 
    where post.datePost = '2010-05-03' 
    and post.threadID = thread.threadID 
    and thread.CatID = 3 
    group by the_day,the_hour 
) s 
group by 1,2,3 

拆分获得星期几作为文本,使用

case dayofweek(date) when 1 then 'sunday' when 2 then 'monday' .... end as dayofweek 

为额外的百分比做

select datePost as daytime, 
    HOUR(timePost) as thehour, 
    count(TEXT) as thecount, 
    count(TEXT)/thecount_daily as percent_this_hour 
    from post 
    inner join thread on post.threadID = thread.threadID 
    inner join ( select datePost as daytime_daily, 
       count(TEXT) as thecount_daily 
       from post inner join thread on post.threadID = thread.threadID 
       where date(post.datePost) BETWEEN '2010-05-01' AND '2010-05-31' 
       and thread.CatID = 3 
       group by datePost)daily on daily.daytime_daily=datepost 



    where date(post.datePost) BETWEEN '2010-05-01' AND '2010-05-31' 

    and thread.CatID = 3 
    group by datePost, thehour 

每小时平均在该时间范围内,

select datePost as daytime, 
    HOUR(timePost) as thehour, 
    count(TEXT) as thecount, 
    hourly_average 
    from post 
    inner join thread on post.threadID = thread.threadID 
    inner join ( select hour(timepost) as daytime_daily, 
       count(TEXT)/count(distinct datePost) as hourly_average 
       from post inner join thread on post.threadID = thread.threadID 
       where date(post.datePost) BETWEEN '2010-05-01' AND '2010-05-31' 
       and thread.CatID = 3 
       group by datePost)daily on daily.daytime_daily=hour(timepost) 



    where date(post.datePost) BETWEEN '2010-05-01' AND '2010-05-31' 

    and thread.CatID = 3 
    group by datePost, thehour 
+0

感谢您的答复。对不起,我不明白你的意思是分裂的? –

+0

按月份,日期,小时。你基本上是把分组的行“拆分”成这些较小的组 – AdrianBR

+0

我对查询“post.datePost BETWEEN'2010-05-01'AND'2010-05-31'”做了一些修改,我对平均值有一些问题功能。我更新了上面的问题。谢谢 –