Average difference between two dates, grouped by a third field?

前端 未结 2 876
夕颜
夕颜 2020-12-20 14:44

So say we have 3 fields, username, start_date, end_date

Users start and stop multiple records, eg below bob has started and stopped two records.

相关标签:
2条回答
  • 2020-12-20 15:16

    You don't specify the granularity you want for the diff. This does it in days:

    select username, avg(end_date - start_date) as avg_days
    from mytable
    group by username
    

    If you want the difference in seconds, use datediff():

    select username, avg(datediff(ss, start_date, end_date)) as avg_seconds
    ...
    

    datediff can measure the diff in any time unit up to years by varying the first parameter, which can be ss, mi, hh, dd, wk, mm or yy.

    0 讨论(0)
  • 2020-12-20 15:17
    SELECT username, AVG(TIMESTAMPDIFF(HOUR, start_date, end_date))
    FROM table
    GROUP BY username
    
    0 讨论(0)
提交回复
热议问题