Php 有条件的平均数
我的问题是:Php 有条件的平均数,php,mysql,Php,Mysql,我的问题是: 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' A
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\u id
的行的平均值
如果两行具有相同的beh_id
,那么我需要先找到这两行结果列的平均值,然后再找到所有项的平均值。可能类似于
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
因为你想要的似乎是平均数的平均值
(我还对查询进行了一些重构,因为您需要的是rater表上的联接)如果您想要的是得到一个带有[
beh_id
,average]的结果,那么您的查询应该是:
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
听起来你需要一个
groupby
子句,但不确定你到底在说什么。