【问题标题】:Selecting rows based on time interval根据时间间隔选择行
【发布时间】:2014-10-03 06:53:52
【问题描述】:

左撇子说我有一张桌子-> 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

现在我想在每个月的时间间隔

获得特定thread_id中的cmets总数COUNT()

所以我有一个像这样的数组 - > (如果我们取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 个查询来做到这一点,但这不是太好。

任何人都可以通过一个查询来完成吗?

【问题讨论】:

    标签: php mysql sql datetime group-by


    【解决方案1】:

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

    -- 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
    

    【讨论】:

      【解决方案2】:

      是的,您可以通过使用 group by 语句来做到这一点:-

      这里是 Sql:-

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

      【讨论】:

      • 显然,如果给定月份没有 cmets,则结果中将不存在该月份。
      • 您也可以使用UNION 来显示所有月份。
      • 如果我还需要显示没有 cmets 的月份怎么办? @nobodynoone
      • 使用UNION 12 次并将其与您的表连接,然后您可以按 cmets 的数量来区分月份值:)
      猜你喜欢
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 2011-01-02
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多