输入年份和月份,例如('2018,2020','1,2,4,5')并返回带有每个月份名称的年份

时间:2018-07-29 10:26:50

标签: sql oracle plsql

输入年份和月份,例如('2018,2020','1,2,4,5'),然后返回带有每个月名称的年份。

i.e - 2018-jan
      2020-jan
      2018-feb
      2020-feb
      ..
      ..

1 个答案:

答案 0 :(得分:1)

这里是如何,缓慢而谨慎地

SQL> with test (col) as
  2    (select q'[('2018,2020','1,2,4,5')]' from dual),
  3  t_years as
  4    (select substr(col, instr(col, chr(39), 1, 1) + 1,
  5                        instr(col, chr(39), 1, 2) - instr(col, chr(39), 1, 1) - 1) yrs
  6     from test
  7    ),
  8  t_months as
  9    (select substr(col, instr(col, chr(39), 1, 3) + 1,
 10                        instr(col, chr(39), 1, 4) - instr(col, chr(39), 1, 3) - 1) mon
 11     from test
 12    ),
 13  row_years as
 14    (select regexp_substr(ty.yrs, '[^,]+', 1, level) yrs
 15     from t_years ty
 16     connect by level <= regexp_count(ty.yrs, ',') + 1
 17    ),
 18  row_months as
 19    (select regexp_substr(tm.mon, '[^,]+', 1, level) mon
 20     from t_months tm
 21     connect by level <= regexp_count(tm.mon, ',') + 1
 22    )
 23  select
 24    to_char(to_date(ry.yrs ||' '|| rm.mon, 'yyyy mm'), 'yyyy mon') result
 25  from row_years ry cross join row_months rm;

RESULT
-----------------
2018 jan
2018 feb
2018 apr
2018 may
2020 jan
2020 feb
2020 apr
2020 may

8 rows selected.

SQL>
  • t_yearst_months分别从输入字符串中提取2018,20201,2,4,5
  • row_yearsrow_months拆分为
  • 最终结果表示row_yearsrow_months之间的交叉联接,其值已连接并具有适当的功能(TO_CHARTO_DATE)并应用了适当的格式掩码给他们