SQL 如何根据数据列将具有日期范围的行转换为具有带间隙的日期范围的多行
SQL how to convert row with date range to many rows with date range with gaps based on a data column
我想根据列将数据行转换为 sql 中的日期范围。
以下是示例数据:
Current Data
FROMDATE TODATE Data
1/01/2010 31/10/2010 100
1/01/2011 31/12/2011 50
1/01/2012 31/12/2012 50
1/01/2013 31/12/2013 50
1/01/2014 31/12/2014 50
1/01/2015 12/10/2015 50
13/10/2015 31/12/2015 50
1/01/2016 21/02/2016 50
22/02/2016 31/12/2016 67
1/01/2017 2/10/2017 67
3/10/2017 31/12/2017 75
1/01/2018 31/03/2018 75
1/04/2018 30/06/2018 75
1/07/2018 31/10/2018 40
1/11/2018 31/12/2018 75
1/01/2019 31/03/2019 75
1/04/2019 31/12/2019 75
1/01/2020 1/03/2020 75
要求的结果是:
FROMDATE TODATE Data
1/01/2010 31/10/2010 100
1/01/2011 21/02/2016 50
22/02/2016 2/10/2017 67
3/10/2017 30/06/2018 75
1/07/2018 31/10/2018 40
1/11/2018 1/03/2020 75
Required List
我想感谢@Gordon Linoff,他 answer 中的一位帮助我解决了 Gaps 和 islands 问题,我只是与您分享这些问题。
我之所以将此作为答案发布是因为标题可以在此类问题的搜索结果中找到
我已经使用 Oracle 数据库完成了它,它应该适用于所有标准 sql 数据库。 dbfiddle供参考
SELECT t.key_id
,MIN(fromdate)
,MAX(todate)
FROM (SELECT t.*
,row_number() over(ORDER BY fromdate) AS startseq
,row_number() over(PARTITION BY t.key_id ORDER BY fromdate) AS endseq
FROM some_table t) t
GROUP BY t.key_id
,(startseq - endseq);
我想根据列将数据行转换为 sql 中的日期范围。 以下是示例数据:
Current Data
FROMDATE TODATE Data
1/01/2010 31/10/2010 100
1/01/2011 31/12/2011 50
1/01/2012 31/12/2012 50
1/01/2013 31/12/2013 50
1/01/2014 31/12/2014 50
1/01/2015 12/10/2015 50
13/10/2015 31/12/2015 50
1/01/2016 21/02/2016 50
22/02/2016 31/12/2016 67
1/01/2017 2/10/2017 67
3/10/2017 31/12/2017 75
1/01/2018 31/03/2018 75
1/04/2018 30/06/2018 75
1/07/2018 31/10/2018 40
1/11/2018 31/12/2018 75
1/01/2019 31/03/2019 75
1/04/2019 31/12/2019 75
1/01/2020 1/03/2020 75
要求的结果是:
FROMDATE TODATE Data
1/01/2010 31/10/2010 100
1/01/2011 21/02/2016 50
22/02/2016 2/10/2017 67
3/10/2017 30/06/2018 75
1/07/2018 31/10/2018 40
1/11/2018 1/03/2020 75
Required List
我想感谢@Gordon Linoff,他 answer 中的一位帮助我解决了 Gaps 和 islands 问题,我只是与您分享这些问题。
我之所以将此作为答案发布是因为标题可以在此类问题的搜索结果中找到
我已经使用 Oracle 数据库完成了它,它应该适用于所有标准 sql 数据库。 dbfiddle供参考
SELECT t.key_id
,MIN(fromdate)
,MAX(todate)
FROM (SELECT t.*
,row_number() over(ORDER BY fromdate) AS startseq
,row_number() over(PARTITION BY t.key_id ORDER BY fromdate) AS endseq
FROM some_table t) t
GROUP BY t.key_id
,(startseq - endseq);