SQL 对没有日期间隔的连续行进行分组
SQL Grouping consecutive rows without date gaps
我遇到以下问题:在以下查询中,我有一个带有开始和结束时间戳的会议列表。我需要知道哪些会议是连续的,没有任何间隔,我需要对这些结果进行分组。
这是原始数据集:
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 陈述中更进一步。
有人可以帮我吗?
这是一个查询,显示没有先前会议的会议:[=15=]
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;
这是一个 SQL小提琴:http://www.sqlfiddle.com/#!9/79676/8。
它是在 MySQL 中完成的,但它应该适用于任何平台,因为这只是标准 SQL。
我遇到以下问题:在以下查询中,我有一个带有开始和结束时间戳的会议列表。我需要知道哪些会议是连续的,没有任何间隔,我需要对这些结果进行分组。
这是原始数据集:
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 陈述中更进一步。
有人可以帮我吗?
这是一个查询,显示没有先前会议的会议:[=15=]
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;
这是一个 SQL小提琴:http://www.sqlfiddle.com/#!9/79676/8。 它是在 MySQL 中完成的,但它应该适用于任何平台,因为这只是标准 SQL。