我有以下问题:在以下查询中,我有一个包含开始和结束时间戳的会议列表。我需要知道哪些会议是连续的,没有任何差距,我需要对这些结果进行分组。
这是原始数据集:
DATE LOCATION START END 2015-04-09 00:00:00 6 1100 1200 2015-04-09 00:00:00 6 1000 1100 2015-04-09 00:00:00 6 1200 1300 2015-04-09 00:00:00 6 1300 1400 2015-04-09 00:00:00 6 1500 1600 2015-04-09 00:00:00 6 1600 1700
在此数据集中,以下记录被认为是连续的,没有时间间隔:
DATE LOCATION START END -- CONSECUTIVE MEETINGS GROUP 1 2015-04-09 00:00:00 6 1000 1100 2015-04-09 00:00:00 6 1100 1200 2015-04-09 00:00:00 6 1200 1300 2015-04-09 00:00:00 6 1300 1400 -- CONSECUTIVE MEETINGS GROUP 2 2015-04-09 00:00:00 6 1500 1600 2015-04-09 00:00:00 6 1600 1700
这就是我想要实现的目标:
DATE LOCATION COUNT 2015-04-09 00:00:00 6 2
目前我无法参加超过两次的连续会议。我可以在11:00 - 12:00到12:00 - 13:00参加会议,但我的SQL语句中的内容不能超过。
有人可以帮帮我吗?
答案 0 :(得分:1)
这是一个查询,显示没有前一次会议的会议:
select *
from Meetings m_after
left join Meetings m_before
on m_before.end = m_after.start
and m_before.date = m_after.date
and m_before.location = m_after.location
where m_before.location is null;
这些基本上是您想要计算的群体的开始会议。
因此,让我们对它们进行统计,按date
和location:
进行分组
select
m_after.date,
m_after.location,
count(*) as Count
from Meetings m_after
left join Meetings m_before
on m_before.end = m_after.start
and m_before.date = m_after.date
and m_before.location = m_after.location
where m_before.location is null
group by m_after.date, m_after.location;
这是一个SQLFiddle:http://www.sqlfiddle.com/#!9/79676/8。 它是在MySQL中完成的,但它应该适用于任何平台,因为这只是标准的SQL。