使用子查询创建视图并在Oracle

时间:2016-05-29 17:04:09

标签: sql oracle view group-by subquery

要检索特定数据集,我必须在选择查询中使用子查询,该查询是按表达式分组,如下所示:

SELECT SUM(b.RESERVEDROOMS) AS "Reserved Rooms",
       (SELECT country
          FROM location
         WHERE location_id = b.location_id) AS "Country"
  FROM bookingsRevenue b,
       location l
 WHERE b.location_id = l.location_id 
 GROUP BY b.location_id

它工作正常并且检索到正确的数据但是当我尝试从中创建视图时,会显示以下错误。你能帮我解决这个问题。

  

[错误]执行(21:74):ORA-00979:不是GROUP BY表达式

1 个答案:

答案 0 :(得分:2)

似乎您的源代码中存在一些混淆。 GROUP BY子句不正确,您也不需要使用相关子查询。 试试这个:

SELECT SUM(b.RESERVEDROOMS) AS "Reserved Rooms", l.country AS "Country"
FROM bookingsRevenue b
JOIN location l ON (b.location_id = l.location_id)
GROUP BY l.country;

如果您还希望将location_id分组,则:

SELECT SUM(b.RESERVEDROOMS) AS "Reserved Rooms", b.location_id, l.country AS "Country"
FROM bookingsRevenue b
JOIN location l ON (b.location_id = l.location_id)
GROUP BY b.location_id, l.country;