Oracle SQL,列名给出 ORA-00911: 无效字符

Oracle SQL, column name gives ORA-00911: invalid character

我通过数据透视语句创建了一个table,它会自动创建一些以数字开头的变量名。

create table MYTAB as
select *
from (select x, anno, v, delta from tab_a13_2 where anno in(2017,2018,2019))
pivot(sum(v)  as v, sum(delta) as d for anno in (2017,2018,2019)) 
where ordine > 0
order by ordine;

select * from MYTAB;
x 2017_V    2017_D  2018_V  2018_D  2019_V  2019_D
1   1.01    -3.18     1.04   11.18    0.96   -6.87
2   1.28     0.09     1.28    7.33    1.25   -1.49
...

但是,如果我尝试在 select 中指定列名,我会收到此错误:

select x,
       2017_V, 2018_V, 2019_V,
       2017_D, 2018_D, 2019_D 
from MYTAB;

Error at line 5:
ORA-00911: invalid character
           2017_V, 2018_V, 2019_V,
               ^
1 statement failed.

我不明白。要么我不允许创建以数字开头的列名,因此 table 创建应该失败,要么我应该能够使用它们。 我检查过列名没有被引用,即 '2017_V'.

一个选项是当您创建 table 时,不要创建以数字开头的列。执行 PIVOT 时,您可以为 IN 子句中的值设置别名,以便从数据透视生成的列更加用户友好。尝试使用如下语句创建您的 table:

  SELECT *
    FROM (SELECT x,
                 anno,
                 v,
                 delta
            FROM tab_a13_2
           WHERE anno IN (2017, 2018, 2019))
         PIVOT (SUM (v) AS v, SUM (delta) AS d
               FOR anno
               IN (2017 AS year_2017, 2018 AS year_2018, 2019 AS year_2019))
   WHERE ordine > 0
ORDER BY ordine;

来自 Database Object Names and Qualifiers 文档:

Database Object Naming Rules

Every database object has a name. In a SQL statement, you represent the name of an object with a quoted identifier or a nonquoted identifier.

  • A quoted identifier begins and ends with double quotation marks ("). If you name a schema object using a quoted identifier, then you must use the double quotation marks whenever you refer to that object.
  • A nonquoted identifier is not surrounded by any punctuation.

...

  1. Nonquoted identifiers must begin with an alphabetic character from your database character set. Quoted identifiers can begin with any character.

您有一个以数字开头的标识符。这告诉您解决方案是使用带引号的标识符并用双引号将列名括起来:

select x,
       "2017_V",
       "2018_V",
       "2019_V",
       "2017_D",
       "2018_D",
       "2019_D" 
from   MYTAB;