一个月的小时 - mysql查询

时间:2018-03-07 08:03:33

标签: mysql sql hour

我有这个查询意味着计算小时数 本月的小时数,包括当前月份的当月 是否有更有效的方式来编写此查询?

SELECT DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m') as month,
     CASE WHEN DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')
     THEN (DAYOFMONTH(NOW())*24)+ HOUR(NOW()) + (MINUTE(NOW())/60) + (SECOND(NOW())/3600) 
     ELSE DAY(LAST_DAY(DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m-%d')))*24
     END As hours
  FROM table1 
 GROUP 
     BY DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m')

1 个答案:

答案 0 :(得分:0)

您可以使用特定的mysql日期和时间函数

  SELECT month(FROM_UNIXTIME(created_at)) as month,
        CASE WHEN month(FROM_UNIXTIME(created_at)) = month(now())
                THEN  TIMESTAMPDIFF(HOUR,DATE_FORMAT(NOW() ,'%Y-%m-01'),NOW()) 
                ELSE HOUR(LAST_DAY(DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y-%m-%d')))
  END As hours
  FROM table1 
  GROUP BY month(FROM_UNIXTIME(created_at))