views:

291

answers:

2

I have a table called baskets with these columns:

  • basket (name of the basket)
  • colour (colour of the basket)
  • apples (the number of apples in the basket)
  • bananas (the number of bananas in the basket)
  • oranges (the number of oranges in the basket)
  • pears (the number of pears in the basket)
  • peaches (the number of peaches in the basket)

With Query1, I determine the total number of fruit in each basket and I also include the colour of each basket:

SELECT basket, colour, apples+bananas+oranges+pears+peaches AS fruit
FROM baskets;

Query1 consists of three columns:

  • basket
  • colour
  • fruit (total number of fruit in the basket)

With Query2, I determine the average number of fruits there are in all baskets of each colour by drawing the information from the result of Query1:

SELECT DISTINCT
        candidate.colour,
        candidate.fruit
            (SELECT AVG(fruit)
                 FROM Query1 AS average
                 WHERE average.colour = candidate.colour) AS fruit
    FROM Query1 AS candidate;

Query2 consists of two columns:

  • colour
  • fruit

Is it possible to nest these queries so that I may obtain the result of Query2 with only one query?

Your help will be much appreciated. Thank you.

+2  A: 
SELECT colour, AVG(apples+bananas+oranges+pears+peaches) AS fruit
FROM baskets
GROUP by colour;
Alex Martelli
Thanks, Alex. That works.
Geoffrey Van Wyk
+1  A: 

If you want the total fruit by colour of basket you would do something like this:

SELECT colour, SUM(apples+bananas+oranges+pears+peaches) AS totalfruit
FROM baskets
GROUP By colour
DJ
Thanks, DJ. I made a mistake. I meant average number of fruit.
Geoffrey Van Wyk