英文:
How to sum the hour of time based on same id with mysql
问题
Sure, here's the translated part:
"我以前从未做过时间汇总。但想法是从数据库中汇总所有以小时为单位的时间。基于相同的id和时间段。对于下面的示例数据。我想知道id为'57'的人在第4个月工作了多少小时。仅当有开始时间(chkin_type=1)和结束时间(chkin_type=2)时。
所以我知道我必须找到时间差
DATEDIFF(hour, time1, time2)
。但我不知道如何遍历最后一行。
示例数据如下:
我可以执行选择。
select * from checkin_db where uid='57' and month(dtime)='4'
但我卡在这里:
- 如何选择
chkin_type
=1的dtime
以便与chkin_type
=2进行比较 - 如何循环结果并使用
datediff
汇总总时间(以小时为单位)?"
英文:
I never done a time summary before. But the idea is to sum all the time in hour from DB. Based on the same id and time period. For the sample data below. I want to know how many hour in which id '57' working in month 4. Only when there're starting time(chkin_type=1) and ending time (chkin_type=2).
So I know that I have to find the time diff with
DATEDIFF(hour, time1, time2)
. But I don't know how to loop through the last row.
Sample data
I can do the select.
select * from checkin_db where uid='57' and month(dtime)='4'
But I stuck here:
- How to select
dtime
wherechkin_type
=1 to compare withchkin_type
=2 - How to loop the result and sum the total time in hours with
datediff
?
答案1
得分: 1
以下是翻译好的部分:
数据需要进行数据透视,然后可以计算时间差,然后将它们相加。
由于MySQL缺乏“pivot”功能,必须使用“CASE WHEN”与聚合函数(在这种情况下是“max()”)来模拟它。
因此,内部查询 'pvt' 选择所需的数据并进行数据透视。
第二级查询 'mins' 计算每天的分钟时间差并求和结果。
最后,外部查询将时间拆分为小时和分钟。
请记住,只有在两个时间值在同一天时才能正常工作。
英文:
The data has to be pivoted and then it is possible to calculate the time differences and then sum them.
Since MySql lacks pivot functionality it must be simulated using CASE WHEN together with an aggregate function (in this case max())
So the inner query 'pvt' selects the wanted data and pivots it.
The second-level query 'mins' calculates the time difference in minutes for each day and sums the results.
Finally the outer query splits the time in hour and minutes.
Keep in mind that all this can work only if the two time values are in the same day.
SELECT total_minutes DIV 60 as hours, total_minutes MOD 60 as minutes
FROM (
SELECT sum(timestampdiff(MINUTE, time1, time2)) as total_minutes
FROM (
SELECT date(dtime) as date,
max(CASE WHEN ckin_type = 1 THEN time(dtime) ELSE NULL END) as time1,
max(CASE WHEN ckin_type = 2 THEN time(dtime) ELSE NULL END) as time2
FROM checkin_db
WHERE uid='57' and month(dtime)='4'
GROUP BY date(dtime)
) pvt
WHERE time1 IS NOT NULL
AND time2 IS NOT NULL
) mins;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论