将日期范围透视为多行

Pivot a Date Range into multiple rows

我有一个 table T 这种格式:

ClientName StartMonth EndingMonth
X Dec 2018 Jan 2021

我希望我的查询输出为:

ClientName MonthRange Year #
X Dec 2018-Nov 2019 1
X Dec 2019-Nov 2020 2
X Dec 2020-Nov 2021 3

谁能帮我解决这个问题的最佳方法是什么?

试试这个:

WITH
indata(clientname,startmonth,endmonth) AS(
  SELECT 'x',DATE '2018-12-01', DATE '2021-01-01'
)
,
-- a series of at least 3 integers - no other way ...
y(y) AS (
          SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
)
SELECT 
  clientname
,  TO_CHAR(ADD_MONTHS(startmonth,(y-1)*12),'Mon-YYYY')
 ||'-'
 ||TO_CHAR(ADD_MONTHS(startmonth,(y-1)*12+11),'Mon-YYYY') AS monthrange
, y AS "year#"
FROM indata CROSS JOIN y
WHERE ADD_MONTHS(startmonth,(y-1)*12) <= endmonth
ORDER BY y;

clientname|monthrange       |year#
x         |Dec-2018-Nov-2019|    1
x         |Dec-2019-Nov-2020|    2
x         |Dec-2020-Nov-2021|    3