Mysql 展开并分组以映射范围内的所有日期
我有一个包含映射和有效日期范围的表,如下所示:Mysql 展开并分组以映射范围内的所有日期,mysql,sql,Mysql,Sql,我有一个包含映射和有效日期范围的表,如下所示: | foo_id | identifier_type | value | start_date | end_date | |--------|-----------------|-------|------------|------------| | 1 | colour | red | 1994-01-01 | 1997-04-01 | | 1 | colour | blue
| foo_id | identifier_type | value | start_date | end_date |
|--------|-----------------|-------|------------|------------|
| 1 | colour | red | 1994-01-01 | 1997-04-01 |
| 1 | colour | blue | 1997-04-18 | 2100-12-31 |
| 2 | value | 7 | 2000-01-01 | 2100-12-31 |
但我想选择数据,以便在没有有效映射时看到范围
| foo_id | identifier_type | value | start_date | end_date |
|--------|-----------------|-------|------------|------------|
| 1 | colour | NULL | 1990-01-01 | 1994-03-31 |
| 1 | colour | red | 1994-01-01 | 1997-04-01 |
| 1 | colour | NULL | 1997-04-02 | 1997-04-17 |
| 1 | colour | blue | 1997-04-18 | 2100-12-31 |
| 2 | value | NULL | 1990-01-01 | 1999-12-31 |
| 2 | value | 7 | 2000-01-01 | 2100-12-31 |
也就是说,对于表中的每个id和标识符类型,我希望看到在我可以指定的范围内表示任意两个日期之间的任何空映射的行
我可以这样做的一种方法是选择所有独特的组合,以及范围内的所有日期。然后在映射上进行左连接。然后最后根据值将所有映射重新分组在一起。但是有没有更简单的方法呢?您可以使用UNIONALL和some填充逻辑
select foo_id, identifier_type, value, start_date, end_date
from t
union all
-- add the first record
select foo_id, identifier_type, NULL, '1990-01-01',
start_date - interval 1 day
from (select t.*,
row_number() over (partition by foo_id, identifier_type order by start_date) as seqnum
from t
) t
where seqnum = 1 and start_date > '1990-01-01'
union all
-- add the rest
select foo_id, identifier_type, null, end_date,
coalesce(next_start_date - interval 1 day, '2100-12-31')
from (select t.*,
lead(start_date) over (partition by foo_id, identifier_type order by start_date) as next_start_date
from t
) t
where next_start_date <> end_date + interval 1 day and
end_date <> '2100-12-31';
是个傻瓜。第一次得到@Gordon Linoff的答案让我很开心。