0

我有一个带有一些评分的 SQL 查询,例如

location, cleanliness, money, kitchen, checkinprocess, servicebyowner

对于很少的数据checkinprocessservicebyowner都是0。我只想计算这些值的平均值。

我想检查我的查询,例如,如果有 20 行作为结果,则必须仅针对现有行计算平均值checkinprocessserviceby owner如果仅针对 10 行结果中的 2 行),它必须仅计算 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 的行。

4

1 回答 1

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),因此平均值始终是浮点数。这在所有数据库中都不是必需的。

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

于 2012-10-01T13:37:57.300 回答