组合多个SQL查询

时间:2009-05-15 00:32:59

标签: sql database

我想查询列出花费比普通猫要长的猫? 我有五张桌子:

Animal,Sale,AnimalOrderItem,AnimalOrder和SaleAnimal

  

动物表:AnimalID,名称,类别   (猫,狗,鱼)

     

SaleAnimal表:SaleID,AnimalID,   SalePrice

     

销售表:SaleID,日期,employeeID,   客户id

     

AnimalOrderItem表:OrderID,   AnimalID,费用

     

AnimalOrder:OrderID,OrderDate,   ReceivingDate,        SupplierID,ShippingCost,EmployeeID

还有其他表我认为它们对查询没有影响。

我想到了以下内容......查询计算所有前期销售天数:

[SaleDate]-[ReceiveDate] AS DaysToSell
Have the INNER JOIN built:
Sale INNER JOIN ((AnimalOrder INNER JOIN (Animal INNER JOIN AnimalOrderItem
ON Animal.AnimalID = AnimalOrderItem.AnimalID) ON AnimalOrder.
OrderID = AnimalOrderItem.OrderID) INNER JOIN SaleAnimal ON Animal.
AnimalID = SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleID

根据上述查询

创建另一个查询
SELECT AnimalID, Name, Category, DaysToSell
WHERE Category="Cat" AND DaysToSell>
(SELECT Avg(DaysToSell)
FROM the earlier query
WHERE Category="Cat"
ORDER BY DaysToSell DESC;

运行查询后,我收到错误

  

ORA-00921:SQL意外结束   命令

任何建议!请

3 个答案:

答案 0 :(得分:1)

查询可以与子查询结合使用。例如,

select *
from (
    select * 
    from mytable
) subquery

将此模式应用于您的问题似乎相当简单。

答案 1 :(得分:0)

我没有看到与select avg匹配的闭括号

答案 2 :(得分:0)

好的,我想出了这个:

    SELECT AnimalID, Name, Category,
           [SaleDate]-[ReceiveDate] AS DaysToSell
    FROM   Sale INNER JOIN ((AnimalOrder INNER JOIN (Animal INNER JOIN AnimalOrderItem ON Animal.AnimalID = AnimalOrderItem.AnimalID) ON AnimalOrder.OrderID = AnimalOrderItem.OrderID)
           INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleID
    WHERE  Category = "Cat"
    AND    ([SaleDate]-[ReceiveDate]) > (SELECT AVG([SaleDate]-[ReceiveDate])
                                         FROM   Sale INNER JOIN ((AnimalOrder INNER JOIN (Animal INNER JOIN AnimalOrderItem ON Animal.AnimalID = AnimalOrderItem.AnimalID) ON AnimalOrder.OrderID = AnimalOrderItem.OrderID)
                                         INNER JOIN SaleAnimal ON Animal.AnimalID =SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleID
                                         WHERE Category = "Cat")
    ORDER BY ([SaleDate]-[ReceiveDate]) DESC;