2014-02-14 232 views
3

我的查询是:平均的平均使用条件

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]' 
     ) 

在这里,我会得到结果的所有平均:

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 

但我需要找到均线与行平均相同的beh_id

如果两行有相同的beh_id那么我需要首先找到这两行的结果列的平均值,然后找到所有项目的平均值。

+1

听起来像你需要一个'group by'子句,但不知道你到底在做什么。 –

回答

0

也许某事像

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 

,因为你想要的东西似乎是平均数的平均值。

(我也重构了一下查询,因为你想要的是一个连接上评价者表)

1

如果你想要的是让与[beh_id,平均],然后将查询应结果是:

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