1

表:主键已突出显示

  1. 客户(customer_id,f_name,l_name,tel_no,addr,nic,city)
  2. 产品(product_id,名称,描述,价格,sales_tax)
  3. 分支(branch_id,名称,电话号码,地址,城市)
  4. 订单(order_id,customer_id,order_date,branch_id)
  5. order_product( order_id,product_id ,数量)

这是我的查询的一个非常简化的版本:

SELECT customer_id, SUM(quantity) AS avg_quantity
FROM orders,order_product
WHERE orders.order_id = order_product.order_id
GROUP BY customer_id
HAVING SUM(quantity) > (SELECT AVG(no_quantity)
FROM(
  SELECT customer_id, SUM(quantity) AS no_quantity
  FROM orders,order_product
  WHERE orders.order_id = order_product.order_id
  GROUP BY customer_id))

我有 2 个子查询,我想在查询执行时临时存储结果集。我见过这样做的 SQL 示例:

(SELECT * FROM orders WHERE branch_id = 4) AS tempone

我想存储结果集,这样我就可以在子查询的上层使用它。上面的查询不在 oracle sql developer 中运行。

ERROR : ORA-00933: SQL command not properly ended
00933. 00000 -  "SQL command not properly ended"

我不想使用临时表。我已经尝试过 WITH AS 子句,查询执行时间太长,超过 20 分钟。我不知道为什么

4

1 回答 1

0

您应该能够通过以下方式简化此操作:

select customer_id, avg_quantity
  from (select customer_id,
               sum(quantity) as avg_quantity,
               avg(sum(quantity)) over () global_avg_quantity
          from orders,
               order_product
         where orders.order_id = order_product.order_id
         group by customer_id)
 where avg_quantity > global_avg_quantity;

但我看到你把SUM(quantity) AS avg_quantity 数量的总和=平均值?

于 2012-12-19T14:57:12.310 回答