根据剧院日期之间的差距生成结果

Generating results based on gap between dates for a theatre

我正在处理 SQL 查询,其中我有 2 个 table 名为 Theatre, Movies like this:

剧院

Theatre with columns theatre id and show date:

id      show_date
------------------
1       2018-05-01
2       2018-05-01
1       2018-05-03
3       2018-05-04
2       2018-05-14
3       2018-05-11
2       2018-05-14

电影

Movie with columns movie id and movie name:

id  name
----------
1   Avatar
2   Spiderman
3   Avengers

一家影院定期放映相同的电影,直到该特定影院的放映日期差异超过 2 天。

对于剧院,如果放映日期相差超过 2 天,它将更改为电影列表中的下一部电影 table。

所有影院按相同顺序放映电影。

现在我想为这个场景写一个查询。

预期的输出是:(我为每一行添加了注释作为解释)

theatre_id  show_date   movie
---------------------------------------------

1           2018-05-01  Avatar  /* 1st theatre, 1st date occurrence so picking 1st movie
2           2018-05-01  Avatar  /* 2nd theatre, 1st date occurrence so picking 1st movie */
1           2018-05-03  Avatar  /* 1st theatre, with 1 day gap (1st may 2018 to 3rd may 2018), so picking 1st movie
3           2018-05-04  Avatar  /* 3rd theatre, 1st date occurrence so picking 1st movie */
2           2018-05-10  Spiderman /* 2nd theatre, with 8 days gap (1st may 2018 to 10th may 2018), so picking 2nd movie */
3           2018-05-11  Spiderman /* 3rd theatre, with 6 days gap (4th may 2018 to 11th may 2018) so picking 2nd movie */
2           2018-05-14  Avengers /* 2nd theatre, with 3 days gap (10th may 2018 to 14th may 2018), so picking 3rd movie */

脚本:

drop table if exists theatre;

CREATE TABLE theatre ( 
  id INTEGER NOT NULL,
  show_date date NOT NULL
);

drop table if exists movie;

CREATE TABLE movie ( 
  id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(60) NOT NULL
);


insert into movie values (null, 'Avatar');
insert into movie values (null, 'Spiderman');
insert into movie values (null, 'Avengers');

insert into theatre values( 1, cast('2018-05-01' as date));
insert into theatre values( 2, cast('2018-05-01' as date));
insert into theatre values( 1, cast('2018-05-03' as date));
insert into theatre values( 3, cast('2018-05-04' as date));
insert into theatre values( 2, cast('2018-05-10' as date));
insert into theatre values( 3, cast('2018-05-11' as date));
insert into theatre values( 2, cast('2018-05-14' as date));

有点复杂;这是一种使用 window 函数的方法,可在 MySQL 8.0.

中使用

据我了解您的问题,您需要将 theatre 中的行放入稍后将分配给同一部电影的组中。为此,您可以使用 lag() 检索之前的 show_date,并生成一个 window 总和,每当出现超过 2 天的间隔时该总和就会递增。然后,你可以带上movietable给每个组分配一部电影:

select t.id, t.show_date, m.name movie
from (
    select 
        t.*, 
        sum(case when show_date <= lag_show_date + interval 2 day then 0 else 1 end) 
            over(partition by id order by show_date) grp
    from (
        select 
            t.*, 
            lag(show_date) over(partition by id order by show_date) lag_show_date
        from theatre t
    ) t
) t
inner join (
    select m.*, row_number() over(order by id) grp from movie m
) m
    on m.grp = t.grp