如何建立一个SQL查询返回平均(价格),最小(价格),最大(价格)加入平均(订单),最小(订单),最大(订单)

时间:2011-12-06 20:49:18

标签: sql oracle join

我想创建一个sql查询,它为2个不同的查询一起返回结果。例如,我希望得到以下形式的结果: 产品名称,平均(价格),最小(价格),最大(价格),平均(订单),最小(订单),最大(订单) 目前我有2个以下形式的SQL查询:

select 
  product.name, order.id, avg(price), min(price), max(price) 
from 
  product, order 
where
  product.name = order.product_name and product.name = 'price' 
group by 
  product.name, order.id

select 
  product.name, order.id, avg(order), min(order), max(order) 
from 
  product, order 
where 
  product.name = order.product_name and product.name = 'order' 
group by 
  product.name, order.id

有些产品有价格和订单,有些产品只有价格,有些只有订单。如何编写一个显示所有结果的查询,并加入那些同时具有订单和价格的查询,并显示那些同时包含i行的查询?

2 个答案:

答案 0 :(得分:4)

我认为你需要的是一个完整的外连接,因为行可以在一个表中,也可以在另一个表中,或者两个中都是:

SELECT 
   NVL(t1.name,t2.name) as name,
   NVL(t1.id, t2.id) as id,
   avg_price,
   min_price,
   max_price,
   avg_order,
   min_order,
   max_order
FROM 
(select product.name, order.id, avg(price) as avg_price, min(price) as min_price, max(price) as max_price 
from product, order 
where product.name = order.product_name and product.name = 'price' 
group by product.name, order.id) t1
FULL OUTER JOIN
(select product.name, order.id, avg(order) as avg_order, min(order) as min_order, max(order) as max_order
from product, order 
where product.name = order.product_name and product.name = 'order' 
group by product.name, order.id) t2
ON t1.name = t2.name

答案 1 :(得分:0)

你的查询没有多大意义,所以我必须尝试从你的问题中推断出很多。在询问SQL问题时,最好发布create table脚本和一些示例数据(以及所需的输出)。

以下是我创建的尝试重新创建问题的方案。

CREATE TABLE product(id NUMBER, name VARCHAR2(10));

CREATE TABLE orders(product_name VARCHAR2(10), VALUE NUMBER);

INSERT INTO product
VALUES     (1, 'order');    
INSERT INTO product
VALUES     (1, 'price');    
INSERT INTO product
VALUES     (2, 'order');    
INSERT INTO product
VALUES     (3, 'price');    
INSERT INTO orders
VALUES     ('order', 5);    
INSERT INTO orders
VALUES     ('price', 5);    
COMMIT;

鉴于这种情况,以下查询将提供3行,并在适当的位置填充“订单”和/或“价格”列。

SELECT   p.id,
         AVG(o1.VALUE) as avg_price,
         MIN(o1.VALUE) as min_price,
         MAX(o1.VALUE) as max_price,
         AVG(o2.VALUE) as avg_order,
         MIN(o2.VALUE) as min_order,
         MAX(o2.VALUE) as max_order
FROM             product p
         LEFT JOIN orders o1
              ON p.name = o1.product_name AND p.name = 'price'
         LEFT JOIN orders o2
              ON p.name = o2.product_name AND p.name = 'order'
GROUP BY p.id