Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of average with a condition

Tags:

php

mysql

My query is:

SELECT avg(result) 
FROM `survey_result_full` 
WHERE `comp_id`='$corow[id]' 
    AND rater_type='riwter' 
    AND survey_id='$survey' 
    AND rater_id in (
        SELECT id 
        FROM raters 
        WHERE participate='$id' 
            AND `type`='$rt[id]'
        )

Here I will get all the average of result:

id   survey_id comp_id rater_id rater_type beh_id result 
---- --------- ------- -------- ---------- ------ ------
6198 79        204     180      riwter     573    4 
6576 79        204     181      riwter     573    4 
6577 79        204     181      riwter     574    4 

But I need to find the average of the averages for rows with identical beh_id.

If two rows have the same beh_id then I need to find the average of the result column of these two rows first then find average of all items.


2 Answers

If what you want is to get a result with [beh_id , average], then your query should be:

SELECT beh_id, avg(result) 
  FROM `survey_result_full` 
 WHERE `comp_id`='$corow[id]' 
   AND rater_type='riwter' 
   AND survey_id='$survey' 
   AND rater_id in (
                    SELECT id 
                      FROM raters 
                     WHERE participate='$id' 
                       AND `type`='$rt[id]'
                    )
GROUP BY beh_id
like image 166
Oscar Pérez Avatar answered Sep 07 '25 21:09

Oscar Pérez


maybe sth like

SELECT AVG(avg_results) 
FROM (
    SELECT srf.beh_id, AVG(srf.result) as avg_results
    FROM `survey_result_full` srf, `raters` r 
    WHERE srf.`comp_id`= '$corow[id]' 
    AND srf.rater_type = 'riwter' 
    AND srf.survey_id = '$survey' 
    AND srf.rater_id = r.id 
    AND r.participate ='$id' 
    AND r.`type` = '$rt[id]'
    GROUP BY srf.beh_id) AS avgs

since what you want seems to be an average of averages.

(I've also refactored a bit the query since what you want is a join on the rater table)

like image 33
2 revsPierrOz Avatar answered Sep 07 '25 20:09

2 revsPierrOz