按不同列(包括时差)分组的查询

query that groups by different columns including time difference

我有一个简单的查询 returns 一周的足球比赛。

select game_group, game_name, game_date, game_StartTime, game_EndTime
from Games
where game_date between '10/1/2018' and '10/7/2018'

结果如下:

 Junior   | blue_red     | 10/1 | 8:00  | 8:30
 Junior   | blue_red     | 10/1 | 8:30  | 9:00
 Junior   | blue_green   | 10/1 | 9:00  | 10:30
 Freshman | brown_purple | 10/1 | 12:00 | 12:30
 Freshman | black_white  | 10/1 | 12:30 | 1:00
 Freshman | yellow_pink  | 10/3 | 3:45  | 5:00
 Senior   | blue_orange  | 10/4 | 7:00  | 7:30
 Sophmore | pink_red     | 10/4 | 7:30  | 8:30
 Sophmore | green_purple | 10/4 | 8:30  | 9:00

有没有办法操纵查询,使其按日期和时间对游戏进行分组?逻辑是,将同一组、同一日期且彼此间隔时间在 30 分钟或更短时间内的游戏组合在一起……因此分组因素将是 game_group、game_date,并且game_StartTime 和 game_EndTime 之间相差 30 分钟...

像这样:

您实际需要做的是结合使用多种方法来解决常见问题。

您首先需要使用 "Gaps and Islands" 方法来获得 CTE 或派生的 table,如下所示(使用缩写和部分示例数据以使其简短):

Group   Game     Date   Start   End    GroupSequence
Fr      B-P      10/1   12:00   12:30  1
Fr      B-W      10/1   12:30    1:00  1
Fr      Y-P      10/1    3:45    5:00  2

GroupSequence 是您在 CTE 中使用 "Gaps and Islands" 解决方案计算的人工列。同一组内的所有比赛,同一天,从前一个end到随后的start不到30分钟的比赛将共享相同的GroupSequence

然后你 select 来自那个 CTE,按 GroupDateGroupSequence 分组,使用 GROUP_CONCAT 技术构建 Games 列,并使用 MIN(Start)MAX(End).

构建您的 Time Range