Oracle ORA -932 expected Number 得到 CHAR

Oracle ORA -932 expected Number got CHAR

我是运行下面的查询,似乎无法弄清楚错误在哪里-

select  case when month>=7 then substr(year,3,2)|| '/'||TO_NUMBER( substr(year,3,2))+1
 else to_number(substr(year,3,2))-1 || '/'|| substr(year,3,2) end as fiscal_year
FROM ( SELECT DISTINCT to_Char(extract( year from date)) as year,
 extract( month from date)as MONTH  FROM TABLE )

我想将年份转换为财政年度,例如 19/20、20/21 等

operator precedence rules表示字符串连接发生在添加之前;这个表达式:

substr(year,3,2)|| '/'||TO_NUMBER( substr(year,3,2))+1

被评估为

substr(year,3,2)|| '/'||TO_NUMBER( substr(year,3,2))

and then 它尝试将 1 添加到该字符串结果。因此你得到了错误。

您可以添加括号,使其在连接之前将年份数字加 1:

substr(year,3,2)|| '/'|| (TO_NUMBER( substr(year,3,2))+1)

你也可以在没有那么多字符串操作的情况下做到这一点:

select case when extract (month from your_date) >= 7 then
    to_char(your_date, 'YY') || '/' || to_char(add_months(your_date, 12), 'YY')
  else
    to_char(add_months(your_date, -12), 'YY') || '/' || to_char(your_date, 'YY')
  end as fiscal_year
FROM (
  SELECT DISTINCT trunc(your_date, 'MM') as your_date
  FROM your_table
)

db<>fiddle

当然还有其他选择。