如何解决如何按预订类型计算每分钟时间间隔内sql中的并行预订?
我创建了一个dbfiddle:
如果我有此预订表(为了简化测试,在此进行了简化,它应该更长一些,并具有不同的预订名称):
+---------------------+---------------------+---------+
| tart_time | end_time | booking |
+---------------------+---------------------+---------+
| 2020-09-01 10:00:00 | 2020-09-01 10:10:00 | Tesla |
| 2020-09-01 10:00:00 | 2020-09-01 10:10:00 | Tesla |
| 2020-09-01 10:00:00 | 2020-09-01 10:05:00 | Volvo |
| 2020-09-01 10:05:00 | 2020-09-01 10:10:00 | Tesla |
| 2020-09-01 10:05:00 | 2020-09-01 10:10:00 | Volvo |
| 2020-09-01 10:09:00 | 2020-09-01 10:10:00 | Tesla |
+---------------------+---------------------+---------+
我想创建一个创建该表的SQL查询:
+---------------------+-------+-------+-------+---------+
| start_time | total | Tesla | Volvo | Brand_X |
+---------------------+-------+-------+-------+---------+
| 2020-09-01 10:00:00 | 3 | 2 | 1 | X |
| 2020-09-01 10:01:00 | 3 | 2 | 1 | X |
| 2020-09-01 10:02:00 | 3 | 2 | 1 | X |
| 2020-09-01 10:03:00 | 3 | 2 | 1 | X |
| 2020-09-01 10:04:00 | 3 | 2 | 1 | X |
| 2020-09-01 10:05:00 | 5 | 3 | 2 | X |
| 2020-09-01 10:06:00 | 4 | 3 | 1 | X |
| 2020-09-01 10:07:00 | 4 | 3 | 1 | X |
| 2020-09-01 10:08:00 | 4 | 3 | 1 | X |
| 2020-09-01 10:09:00 | 5 | 4 | 1 | X |
| 2020-09-01 10:10:00 | 5 | 4 | 1 | X |
+---------------------+-------+-------+-------+---------+
在此之前,我得到了一些帮助: How to count concurrently bookings in sql in time interval per minute?
这是我当前的解决方案:
with recursive cte as (
select start_time,end_time,booking
from t
union all
select start_time + interval 1 minute,booking
from cte
where start_time < end_time
),booking_typs as (
select distinct booking
from t
)
select
start_time,count(*) as total,count(if(cte.booking = 'Tesla',cte.booking,NULL)) as Tesla,count(if(cte.booking = 'Volvo',NULL)) as Volvo
from cte
group by start_time
order by start_time
但是我想使其更具动态性,以便它可以动态生成更多列,而不必进行硬编码。我开始在自己的表中获得不同的booking_typs,但是我不知道如何将它们包括在选择中。我可以在代码中做这部分,但我想直接在SQL中做。
我的问题:
- 如何动态添加booking_typs列?
- 我想为MySQL 5.7和MySQL 8.0提供一个解决方案(不一定是相同的解决方案)吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。