gpt4 book ai didi

mysql - 当有多个时间戳时,如何在mysql中按一天中的小时对数据进行分组?

转载 作者:行者123 更新时间:2023-11-29 09:52:57 27 4
gpt4 key购买 nike

我有一个数据集,其中每条记录都有多个时间戳。我正在尝试总结数据集,以按一天中的绝对小时获取每个时间戳的计数。

当只有一个时间戳时,我可以按小时进行分组,但当我有多个时间戳时,我无法执行此操作。

我当前的数据:

MemberID    Appointment_Time    CheckIn_Time    CheckOut_Time
1 12:20pm 01:30pm 05:00pm
2 09:00am 08:30am 04:20pm
3 12:10pm 03:30pm 05:20pm

我想要什么

Hour of the day #Appts  #CheckIns    #Checkouts
8 0 1 0
9 1 0 0
10 0 0 0
11 0 0 0
12 2 0 0
1 0 1 0
2 0 0 0
3 0 1 0
4 0 0 1
5 0 0 2

最佳答案

一种可能的解决方案是使用条件聚合(HOUR 函数假设您使用的是日期/日期时间列):

SELECT hourlist.hh hour_of_day
, COUNT(CASE WHEN HOUR(Appointment_Time) = hourlist.hh THEN 1 END) appts
, COUNT(CASE WHEN HOUR(CheckIn_Time) = hourlist.hh THEN 1 END) checkins
, COUNT(CASE WHEN HOUR(CheckOut_Time) = hourlist.hh THEN 1 END) checkouts
FROM (
SELECT 0 AS hh UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9 UNION ALL
SELECT 10 UNION ALL
SELECT 11 UNION ALL
SELECT 12 UNION ALL
SELECT 13 UNION ALL
SELECT 14 UNION ALL
SELECT 15 UNION ALL
SELECT 16 UNION ALL
SELECT 17 UNION ALL
SELECT 18 UNION ALL
SELECT 19 UNION ALL
SELECT 20 UNION ALL
SELECT 21 UNION ALL
SELECT 22 UNION ALL
SELECT 23
) AS hourlist
LEFT JOIN appointments ON hourlist.hh IN (HOUR(Appointment_Time), HOUR(CheckIn_Time), HOUR(CheckOut_Time))
GROUP BY hourlist.hh

关于mysql - 当有多个时间戳时,如何在mysql中按一天中的小时对数据进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54475132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com