给出日期的时间

时间:2019-12-24 11:32:31

标签: mysql sql

我正试图根据记录的活动连续几天在MySQL中获取报告。我具有给定状态的开始日期和时间以及结束日期和时间。我的目标是接收以下形式的报告:

Status|Date|Sum of activity

我遇到的问题是一些活动开始于2019-12-12 18:21:12,而第二天结束了2019-12-13 03:21:12。是否有一种方法可以说将一个日期的结果拆分为23:59:59,然后将剩余时间添加到第二天?到目前为止,我在下面有一个代码,但这只是将timestampdiff求和。

USE db;
SELECT
  table1.status,
  left(table1.start_time, 7) ' Date',
  sec_to_time(
    sum(
      timestampdiff(
        second,
        table1.start_time,
        (
          case when table1.end_time is null then now() else table1.end_time end
        )
      )
    )
  ) 'Sum of activity'
FROM
  table1
GROUP by 1,2

1 个答案:

答案 0 :(得分:1)

您可以使用date()函数:

select status, date(start_time) as date, count(*) as "Sum of activities"
  from table1
 group by status, date(start_time);

Demo

更新(取决于您的评论):尝试使用

select status, date(start_time) as date, 
       sec_to_time(sum(timestampdiff(second,
                                     start_time,
                                     (case
                                       when end_time is null then
                                        now()
                                       else
                                        end_time
                                     end))))
       as "Sum of activities"
  from table1
 group by status, date(start_time);

Update2 :要完成最后提到的任务,需要首先生成行:

select date1, 
       extract( hour from
       sec_to_time(
                   sum(case
                       when date1 = date(start_time) then
                    timestampdiff(second,start_time,date2)
               when date1 = date(end_time) then
                    timestampdiff(second,date1,end_time)
               else
                    timestampdiff(second,date1,date2)              
               end     
                    )) ) as "Time Difference as hour"
  from
  (
   select @cr := @cr + 1 as rn,       
          date_sub(date(end_time), interval date(end_time)-date(start_time) - @cr + 1 day) as date1,
          date_sub(date(end_time), interval date(end_time)-date(start_time) - @cr day) as date2,
          start_time, end_time
     from information_schema.tables c1 
    cross join ( select @cr := 0 ) r
    cross join table1 t
    where @cr < date(end_time)- date(start_time)+1
  ) q
  group by date1;

Demo 2

删除extract( hour from )部分,可以使整体差异达到第二精度。