0

I have a table with 3 columns: Animal, key, owner. Example

Cat     1     Bob
Bird    2     Bob
dog     3     Bob
dog     4     Andy
Lizard  5     Andy
Bird    6     Andy
Cat     7     Andy

and one related table per animal (columns key, weight). For example, table CAT_WEIGHT:

1   12
7   17

I want to find the Min, Max, Average, Total, and Count for each animal type, but only for a particular owner.

Is this possible to calculate these using a single MYSQL query? I know I can do it in multiple queries but am looking for the best way.

Thanks

1
  • Please note: One or more of the answers below may no longer apply to this question since it has been edited to be quite different from the original question. Commented Feb 15, 2013 at 0:06

2 Answers 2

3

Yes it is possible to do this using just one query.

All other things being equal you want to use as few queries as possible. Roundtrips to the database are generally some of the more expensive things you'll encounter in programs.

select 
  animal, 
  min(weight)   min_weight, 
  max(weight)   max_weight, 
  avg(weight)   avg_weight, 
  sum(weight)   tot_weight, 
  count(weight) cnt_weight
from 
  your_table
group by 
  animal 
order by animal;
Sign up to request clarification or add additional context in comments.

2 Comments

I think this is close. I realized the weight is in another table (see revised questoin). Is it still possible in a single query?
Revising a question such that it is significantly different from the original question is not necessarily something that is done very often. You may wish to open a separate question. Or maybe someone will come along and answer the question as it now stands.
0

How about:

select min(Weight), max(Weight), sum(Weight), count(*) from animals_table group by animal

1 Comment

This would count rows with a NULL weight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.