【问题标题】:SQL error - ORA-00933: SQL command not properly endedSQL 错误 - ORA-00933: SQL 命令未正确结束
【发布时间】:2018-08-05 13:49:17
【问题描述】:

我知道有很多类似的问题以前被问过,但我已经查看了其中的许多问题,但我无法找到解决以下问题的方法。

这是我尝试编写一个查询,显示 3 月份按房间类型划分的预订总数:

 select rt.room_type_id as RoomType
      , count(r.no_of_reservations) as NoOfReservations
 from Room_type rt
    , Room r
    , Reservation res
where rt.room_type_id = r.room_type_id
  and r.room_id = res.room_id
  and extract(month from res.check_in_date) = 3
  and extract(month from res.check_out_date) = 3
order by r.no_of_reservations
group by r.room_type_id;

当我运行此查询时,我收到错误:ERROR at line 11: ORA-00933: SQL command not properly ended

我该如何解决这个问题?我不确定出了什么问题。

【问题讨论】:

  • ORDER BY 子句应该是最后一个语句
  • @NickKrasnov 我进行了更改并得到了错误:ORA-00979: not a GROUP BY expression
  • 书写顺序和SQL查询顺序是。 1. SELECT 2. FROM 3. WHERE 4. GROUP BY 5. ORDER BY
  • 此外,只要有 GROUP BY 子句。您应该只使用分组函数或您分组所依据的列。在您的情况下,它是 rt.room_type_id 而不是 r.room_type_id

标签: sql oracle


【解决方案1】:

你可以使用:

select r.room_type_id as RoomType       -- rt alias changed to r to match group by
      ,count(r.no_of_reservations) as NoOfReservations
from Room_type rt                        -- explicit join
join Room r
  on rt.room_type_id = r.room_type_id
join Reservation res
  on r.room_id = res.room_id
where extract(month from res.check_in_date) = 3
  and extract(month from res.check_out_date) = 3
group by r.room_type_id       --swapped lines group by <=> order by
order by NoOfReservations;    --alias from SELECT

【讨论】:

  • 为什么? Oracle 没有在您尝试过之后告诉您为什么吗?因为 ORA-00979:不是 GROUP BY 表达式。您没有 SELECT 它,因此当语句中包含聚合时,您不能 ORDER BY 它。 Similarly, when selecting DISTINCT values and ordering by a column that isn't part of the SELECT statement, you'd get ORA-01791: not a SELECTed expression.
猜你喜欢
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
相关资源
最近更新 更多