CAST 标识符无效

Invalid identifier with CAST

我在 Oracle DB 12.1.0 中的 table 包含时间戳和值。每 1 秒收集一次值。我只需要保持 1 分钟的平均值。 例如

datetime    value
01.11.2013 0:00:01  10
01.11.2013 0:00:02  20
01.11.2013 0:00:03  10
01.11.2013 0:00:04  20
...
01.11.2013 0:00:59  10

应该return

dt  average
01.11.2013 0:00:00  14,91525424
01.11.2013 0:01:00  ...

我尝试按分钟截断并计算平均值。它在没有 dt 别名的情况下工作。

select cast(trunc(datetime,'mi') as timestamp) dt, avg(value) as average
from my_table
group by dt order by dt

但出现 ORA-00904: "DT": 无效标识符错误。我需要一个别名来将结果插入到新的 table.

不能使用别名进行分组,像这样使用:

select cast(trunc(datetime,'mi') as timestamp) dt, avg(value) as average
from my_table
group by cast(trunc(datetime,'mi') as timestamp) 
order by cast(trunc(datetime,'mi') as timestamp);

cast 并不是真正的问题;您不能在同一级别的查询中使用列表达式别名,但在 order-by 子句中除外。这是因为语句被解析和执行的顺序。 From the docs:

c_alias

Specify an alias for the column expression. Oracle Database will use this alias in the column heading of the result set. The AS keyword is optional. The alias effectively renames the select list item for the duration of the query. The alias can be used in the order_by_clause but not other clauses in the query.

您可以使用子查询,或者在这种情况下只是重复表达式;你甚至不需要包括演员表:

select cast(trunc(datetime,'mi') as timestamp) dt, avg(value) as average
from my_table
group by trunc(datetime,'mi')
order by dt
/

如果你真的想在 group-by 子句中使用别名 - 也许你的真实表达要复杂得多 - 你需要使用内联视图或 CTE:

select dt, avg(value) as average
from (
  select cast(trunc(datetime,'mi') as timestamp) dt, value
  from my_table
)
group by dt
order by dt;