首页 > 解决方案 > 来自错误位置的关键字

问题描述

显示房地产经纪人员工编号,姓名,年薪为年薪,月薪为月薪,年龄为年龄。将月薪四舍五入到小数点后两位。将年龄舍入到岁数。按员工年龄降序对输出进行排序。如果记录中没有出生日期,则将年龄列为“未知”。这是我必须回答问题的代码。

select st_staffno, st_name, st_salary "Annual Salary",(st_salary/12) as "Monthly Salary"   
    decode (st_birthdate, null, 'unknown'), 
    round sysdate ((st.birthdate)/365.25,0) as "Age"
from staff
order by "Age" desc;

它返回 From 关键字 not found where expected 错误。

标签: sqloracle

解决方案


您应该使用您正在使用的 DBMS 标记 SQL 问题。DECODE我断定它是甲骨文。ORA-00923 "FROM keyword not found where expected"当查询解析器认为该SELECT子句已完成但没有FROM关键字跟随时,您会得到。那么是什么让 DBMS 认为该SELECT子句已结束?当您错过所选表达式之间的逗号时,通常会发生这种情况。

你的错误:

  1. 后面少了一个逗号as "Monthly Salary"
  2. 您的年龄计算在语法上是错误的。
  3. 您正在使用st.birthdate,但st查询中没有表名或别名。我想列名是st_birthdate

更正后的查询:

select
  st_staffno,
  st_name,
  st_salary as "Annual Salary",
  st_salary / 12 as "Monthly Salary"   
  decode(st_birthdate, null, 'unknown'), 
  round((sysdate - st_birthdate) / 365.25, 0) as "Age"
from staff
order by "Age" desc;

DECODE也可以使用标准 SQL 的CASE WHEN. 并且要从字面上应用“然后将年龄列为未知”,您必须结合最后两个表达式。而且您缺少“将月薪四舍五入到小数点后两位”。

select
  st_staffno,
  st_name,
  st_salary as "Annual Salary",
  round(st_salary / 12, 2) as "Monthly Salary"   
  case when st_birthdate is null
       then 'unknown'
       else to_char(round((sysdate - st_birthdate) / 365.25, 0))
  end as "Age"
from staff
order by st_birthdate nulls last;

最后:我们通常不会根据一年的实际长度来计算年龄。当我们在 4 月 1 日出生时,我们会在每年的 4 月 1 日午夜满一岁。

extract(year from sysdate) - extract(year from st_birthdate) -
case when to_char(sysdate, 'mmdd') < to_char(st_birthdate, 'mmdd')
  then 1 else 0 
end as "Age"

推荐阅读