views:

726

answers:

3

I want to make a query to list cats that took longer than average cats to sell? I have five tables:

Animal, Sale, AnimalOrderItem, AnimalOrder, and SaleAnimal

Animal table: AnimalID, Name, Category (cat, dog, fish)

SaleAnimal table: SaleID, AnimalID, SalePrice

Sale table: SaleID, date, employeeID, CustomerID

AnimalOrderItem table: OrderID, AnimalID, cost

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

There is other tables I don’t think they have an effect on the query.

I thought of the following ... make a query to calculate days to sell for all ex.:

[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

Create another query based on the above query

SELECT AnimalID, Name, Category, DaysToSell
WHERE Category="Cat" AND DaysToSell>
(SELECT Avg(DaysToSell)
FROM the earlier query
WHERE Category="Cat"
ORDER BY DaysToSell DESC;

After running the query it I got error saying

ORA-00921: unexpected end of SQL command

Any suggestions! please

A: 

I don't see the closed bracket that matches with the select avg

CodeToGlory
thanks for that ...but I really need the help of connecting the two queries together and make it work
A: 

Ok, I've come up with this:

    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;
Nebakanezer
I got missing expression error .. I really appreciate your help guy's
A: 

Queries can be combined with a subquery. For example,

select *
from (
    select * 
    from mytable
) subquery

Applying this pattern to your problem seems fairly straightforward.

Andomar
you mean making it like Nebakanezer suggestion, can you explain with an example please