Oracle 日期格式错误 - ORA-00933: SQL 命令未正确结束

Oracle date formatting error - ORA-00933: SQL command not properly ended

我正在尝试执行一个简单的查询 (ORACLE DB) 来显示两个日期列 (START_TIME & END_TIME) 以及总计数和百分比,并按月份和年份进行过滤数据库中两个日期字段的数据类型定义为日期,我试图以下面的格式显示数据

样本数据无时间戳

start_time - 01.12.2020 
end_time - 02.12.2020

查询

SELECT 
to_char(cast(START_TIME as date),'YYYY') as START_BY_YEAR ,
to_char(cast(END_TIME as date),'YYYY') as END_BY_YEAR ,
to_char(cast(START_TIME as date),'MM.YYYY')as START_BY_MONTH,
to_char(cast(END_TIME as date),'MM.YYYY') as END_BY_MONTH,
to_char(cast(START_TIME as date),'DD.MM.YYYY') as START_BY_DAY,
to_char(cast(END_TIME as date),'DD.MM.YYYY') as END_BY_DAY,
COUNT(*) as count,
round(100*ratio_to_report(count(*)) over (), 4) percentage  
FROM SCHEMA_NAME.TABLE_NAME
WHERE to_char(cast(START_TIME as date),'MM.YYYY')='12.2020'
and to_char(cast(END_TIME as date),'MM.YYYY')='12.2020'
GROUP BY 
START_BY_YEAR,
END_BY_YEAR,
START_BY_MONTH,
END_BY_MONTH,
START_BY_DAY,
END_BY_DAY
order by 
START_BY_YEAR desc,
END_BY_YEAR desc,
START_BY_MONTH desc,
END_BY_MONTH desc,
START_BY_DAY desc,
END_BY_DAY desc

我收到错误消息

ORA-00904: "END_BY_DAY": invalid identifier
  1. 00000 - “%s:无效标识符” *原因:
    *行动: 行错误:19 列:1

我哪里出错了还不清楚

预期结果集

START_BY_YEAR END_BY_YEAR START_BY_MONTH END_BY_MONTH START_BY_DAY END_BY_DAY
2012          2012        12.2012        12.2012      01.12.2020   02.12.2020   

请注意,为了便于阅读,我对代码进行了扩展。

建议?

要解决该错误,您必须从 GROUP BY 子句中删除别名。 此外,如果您的 table 有 date 列,则不需要 CASTs 并且查询可以重新编写为:

SELECT 
    to_char(START_TIME,'YYYY') START_BY_YEAR ,
    to_char(END_TIME,'YYYY') END_BY_YEAR ,
    to_char(START_TIME,'MM.YYYY') START_BY_MONTH,
    to_char(END_TIME,'MM.YYYY') END_BY_MONTH,
    to_char(START_TIME,'DD.MM.YYYY') START_BY_DAY,
    to_char(END_TIME,'DD.MM.YYYY') END_BY_DAY,
    COUNT(*) as count,
    round(100*ratio_to_report(count(*)) over (), 4) percentage  
FROM TABLE_NAME
WHERE to_char(START_TIME,'MM.YYYY')='12.2020'
  and to_char(END_TIME,'MM.YYYY')='12.2020'
GROUP BY 
  to_char(START_TIME,'YYYY') ,
  to_char(END_TIME,'YYYY') ,
  to_char(START_TIME,'MM.YYYY') ,
  to_char(END_TIME,'MM.YYYY') ,
  to_char(START_TIME,'DD.MM.YYYY') ,
  to_char(END_TIME,'DD.MM.YYYY') 
order by 
    START_BY_YEAR desc,
    END_BY_YEAR desc,
    START_BY_MONTH desc,
    END_BY_MONTH desc,
    START_BY_DAY desc,
    END_BY_DAY desc

像这样的table:

create table table_name as
(
    select date '2020-12-01' start_time,
           date '2020-12-02' end_time
    from dual
);

查询给出:

START_BY_YEA END_BY_YEAR  START_BY_MON END_BY_MONTH START_BY_DAY END_BY_DAY   COUNT PERCENTAGE
------------ ------------ ------------ ------------ ------------ ------------ ----- ----------
2020         2020         12.2020      12.2020      01.12.2020   02.12.2020       1        100
1 row selected.

先检查部分结果:

select cast(END_TIME as date),'DD.MM.YYYY') as END_BY_DAY
FROM SCHEMA_NAME.TABLE_NAME

从结果中您可以了解您机器的 NLS 格式并用自定义 to_char 格式包装它。