Average average with the condition

My request:

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 value of the 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 the same beh_id.

If two rows are the same beh_id, then I need to first find the average value of the result column of these two rows, and then find the average value for all the elements.

+3
source share
2 answers

maybe for example

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 the average of averages.

(I also reworked the query a bit since you want to join the rater table)

0
source

If you want to get the 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
+1
source

All Articles