简体   繁体   中英

How can I nest these two SQL queries in MS Access 2007?

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.

SELECT colour, AVG(apples+bananas+oranges+pears+peaches) AS fruit
FROM baskets
GROUP by colour;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM