字段的SQL平均值为0

时间:2012-10-01 13:23:37

标签: php sql

我有一些SQL查询,其中包含一些评级,例如

location, cleanliness, money, kitchen, checkinprocess, servicebyowner

对于少数数据checkinprocessservicebyowner0。我只想计算值的平均值。

我想在我的查询中好像,如果结果有20行,则必须仅针对现有行计算checkinprocessserviceby owner的平均值(如果它仅用于2行) 10行结果)它必须仅计算2行的平均值,但对于其他行,它可以基于行数计算。这是我写的查询:

  select count(customdata) as CNT,
         customdata,
         sum(service_by_owner) as ser,
         sum(checkinprocess) as chk,
         sum(locationrating) as loc,
         sum(cleanlinessrating) as cle,
         sum(valueformoneyrating) as val,
         sum(kitchenequipmentrating) as kit
    from feedback
group by customdata HAVING customdata !='null' AND customdata!=''; 

我能够计算其余四个人的平均值    基于行的字段,但对于这两个字段有点棘手    我

修改

PHP用于计算平均值:

foreach($result as $row){
  $arrValues[] = array("customdata"=>$row['customdata'],
                       "checkinprocess"=>ceil(($row['chk'])),
                       "service_by_owner"=>(ceil($row['ser'])),
                       "valueformoneyrating"=>ceil(($row['val']/($row['CNT']*4))*100), 
                       "locationrating"=>ceil(($row['loc']/($row['CNT']*4))*100),
                       "kitchenequipmentrating"=>ceil(($row['kit']/($row['CNT']*4))*100), 
                       "cleanlinessrating"=>ceil(($row['cle']/($row['CNT']*4))*100));
}

这个checkinprocess和servicebyowner,我必须只计算现有行的平均值,而不是全部为0。

1 个答案:

答案 0 :(得分:0)

有点猜测。 。 。但您似乎希望值的平均值不是0.您可以使用SQL avg函数执行此操作:

select count(customdata) as CNT,
       customdata,
       avg(case when service_by_owner <> 0 then service_by_owner*1.0 end)*4*100.0 as ser,
       avg(case when checkinprocess<> 0 then checkinprocess*1.0 end)*4*100.0  as chk,
       avg(case when locationrating<> 0 then locationrating*1.0 end)*4*100.0  as loc,
       avg(case when cleanlinessrating<> 0 then cleanlinessrating*1.0 end)*4*100.0  as cle,
       avg(case when valueformoneyrating<> 0 then valueformoneyrating*1.0 end)*4*100.0  as val,
       avg(case when kitchenequipmentrating<> 0 then kitchenequipmentrating*1.0 end)*4*100.0  as kit
from feedback
WHERE customdata <> 'null' AND customdata <> ''; 
group by customdata

[乘以4 * 100取决于评论。]

您没有提到您正在使用哪个SQL引擎,因此我将所有值转换为浮点数(乘以1.0),因此平均值始终为浮点数。这在所有数据库中都不是必需的。

我还将HAVING子句更改为WHERE子句。这在某种程度上是一个偏好问题,但我认为这是过滤输入而不是输出。另外,您的意思是customdata <> 'null'还是customdata is not null