根据时间间隔选择行

时间:2014-10-03 06:53:52

标签: php mysql sql datetime group-by

Lefts说我有一张桌子 - > comments

id| comment | thread_id |         time       |  
1    xyz        1         2013-1-10 19:21:17
2    xyz        1         2013-1-11 19:21:17
3    xyz        2         2013-1-14 19:21:17
4    xyz        2         2013-2-10 19:21:17
5    xyz        1         2013-2-10 19:21:17
6    xyz        1         2013-2-10 19:21:17
7    xyz        1         2013-2-10 19:21:17
8    xyz        1         2013-4-10 19:21:17
9    xyz        1         2013-4-10 19:21:17
10   xyz        1         2013-6-10 19:21:17

现在,我希望在每个月的间隔的特定COUNT()内获得总评论thread_id

所以我有一个像这样的数组 - > (如果我们采用thread_id = 1)

$total[0] => 2 
$total[1] => 6
$total[2] => 6 
$total[3] => 8
$total[4] => 8
$total[5] => 9

...等到$ total [11] => 9

我每个月可以通过12个查询来做到这一点,但这不太好。

任何人都可以使用一个查询进行操作吗?

2 个答案:

答案 0 :(得分:0)

是的,您可以使用group by语句执行此操作: -

以下是Sql: -

Select month(time) as Month, COUNT(thread_id) as No_of_Comment from comments group by month(time) 

答案 1 :(得分:0)

要生成完整的月份,您可以使用以下设备,基本上是所有可能值的列表,然后通过左连接将数据附加到此:

-- just an example
SELECT
      *
FROM (
      select 1  as th union all
      select 2  as th union all
      select 3  as th union all
      select 4  as th union all
      select 5  as th union all
      select 6  as th union all
      select 7  as th union all
      select 8  as th union all
      select 9  as th union all
      select 10 as th union all
      select 11 as th union all
      select 12
      ) mon
      LEFT JOIN (
                  SELECT
                        MONTH(time)      AS Month
                      , COUNT(thread_id) AS No_of_Comment
                  FROM comments
                  GROUP BY
                        MONTH(time)
            ) dat
                  ON mon.th = dat.month