Re: Query to get the min of the total
От | Oliveiros d'Azevedo Cristina |
---|---|
Тема | Re: Query to get the min of the total |
Дата | |
Msg-id | 90DB01C16D094EA3A6055DBE39B73EF5@marktestcr.marktest.pt обсуждение исходный текст |
Ответ на | Query to get the min of the total (Marta Pérez Romero <martape@gmail.com>) |
Ответы |
Re: Query to get the min of the total
|
Список | pgsql-novice |
Howdy,
Marta,
have you tried a nested query?
Something like
SELECT petname, MIN(total)
FROM (
SELECT petname,SUM(quantity) as total
FROM pets a
NATURAL JOIN sales b
GROUP BY petname
) x
Best,
Oliveiros
----- Original Message -----From: Marta Pérez RomeroSent: Friday, May 04, 2012 10:43 AMSubject: [NOVICE] Query to get the min of the totalHi All,I am trying to do something but cannot find the way.Hopefully you have some suggestions :)I have two tables, as follows:pets: with these columns: petcode, petname, petprice, petfamilysales: with these columns: salescode, petcode, quantityThe pets table contains all the pets in my pet shop, with the code of the pet, its name, its price and the family it belongs to.So for example:petcode | petname | petprice | petfamily------------------------------------------------------------1 | canary | 5.00 | birds2 | retriever | 12.00 | dogs3 | siamese | 28.00 | cats4 | sparrow | 7.00 | birds5 | poodle | 16.00 | dogsThe sales table tracks all the sales in the shop, with the code of the sale, the code of the pet that was bought, and the quantity of this pet bought.For example:salescode | petcode | quantity----------------------------------------------1 | 1 | 22 | 4 | 53 | 5 | 14 | 2 | 35 | 5 | 86 | 1 | 4Now, I need to build a query that returns the least sold pet, in quantity. It will include the pet name and the quantity sold.So in the example above it will be:petname | quantityretriever | 3Now, the problem I have is that I can´t work with nested aggregations.First I need to get the total quantity by petcode (which will be the sum of quantity). And then get the MIN of the SUM of quantity, which I don´t know how to do.This is the query so far:SELECTpets.petname,sum(sales.quantity)FROM sales INNER JOIN pets ON sales.petcode= pets.petcodeGROUP BYpets.petnameHAVING SUM(sales.quantity)=(SELECT MIN(quantity) FROM sales)ORDER BY pets.petname;But it does not return any result. How can I do it?Thanks very much
В списке pgsql-novice по дате отправления: