views:

28

answers:

2

I'm just learning MySQL - is there a way to combine (or nest) aggregate functions?

Given a query:

SELECT user, count(answer) FROM surveyValues WHERE study='a1' GROUP BY user;

This will give me the number of questions answered by each user. What I really want is the average number of questions answered per user...something like:

SELECT avg(count(answer)) FROM surveyValues WHERE study='a1';

What's the correct way to compute this statistic?

If this is possible, is there a way to then break this statistic down for each question? (users can answer the same question multiple times). Something like:

SELECT avg(count(answer)) FROM surveyValues WHERE study='a1' GROUP BY question;
+3  A: 

You have to use subqueries:

  SELECT x.user, 
         AVG(x.cnt)
    FROM (SELECT user, COUNT(answer) AS cnt
            FROM surveyValues 
           WHERE study='a1' 
        GROUP BY user) x
GROUP BY x.user

You can't wrap an aggregate with another aggregate. You could wrap an analytic in an aggregate, if MySQL supported analytic/ranking/windowing functions...

OMG Ponies
Indeed, subqueries are the answer. If you have more than one query dealing with the number of answers per user, you might consider putting the subquery into a view.
tdammers
Oh man, you can alias columns? SUPER-nifty. (I'm sure that sounded super-naive, but this just made my day). Thanks, works perfectly.
Ender
A: 

yes - those all look reasonable.

Have you tried them and received unexpected results?

usually, i would expect that you also include the driving column in the select list:

SELECT question, avg(count(answer)) 
FROM surveyValues 
WHERE study='a1' 
GROUP BY question; 
Randy