如何设置 mysql 查询和 php 代码忽略值 0 并计算其他行

How to set mysql query and php code to ignore value 0 and calculate other rows

如何设置mysql查询和php代码,我有这个mysql:

CREATE TABLE IF NOT EXISTS `ocene` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `predmeti` varchar(255) NOT NULL,
  `ocena1` varchar(255) NOT NULL,
  `ocena2` varchar(255) NOT NULL,
  `ocena3` varchar(255) NOT NULL,
  `ocena4` varchar(255) NOT NULL,
  `ocena5` varchar(255) NOT NULL,
  `ocena6` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 CHARSET=utf8;

因此 ocena1 需要以下值 - ocena6 的范围可以从 0 到 5。例如,如果:

ocena1 = 5
ocena2 = 4
ocena3 = 0
ocena4 = 0
ocena5 = 0
ocena6 = 2 

该函数应忽略所有值为 0 的行,在本例中,将与 3 共享 11 的总和。我尝试了所有方法,但没有成功。提前致谢。

$con=mysqli_connect("localhost","root","","evidencija_ocena");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

    $sql = "SELECT predmeti,( ocena1 + ocena2 + ocena3 + ocena4 + ocena5 + ocena6) AS prosek FROM ocene group by id";

    if ($result=mysqli_query($con,$sql))
    {
    // Fetch one and one row
    while ($row=mysqli_fetch_row($result))
      {
      printf ("%s (%s) <br />",$row[0],$row[1]);
      }
    // Free result set
    mysqli_free_result($result);
  }


  $sql = "SELECT  SUM(prosek) FROM ocene";   
  if ($result=mysqli_query($con,$sql))
  {
  // Print out result
while ($row = mysqli_fetch_array($result)){
    echo "PROSEK" . $row['SUM(predmeti)'] . "" ;
       echo "<br />";
}
  }

  mysqli_close($con);

并且:

$brojOcena = 0
$suma = 0
if($ocena1 > 0) {
    $suma += $ocena1;
    $brojOcena += 1;
}

if($ocena2 > 0) {
    $suma += $ocena2;
    $brojOcena += 1;
}

if($ocena3 > 0) {
    $suma += $ocena3;
    $brojOcena += 1;
}

...

$prosek = $suma / $brojOcena

如果你想得到非零列的个数,你可以这样做:

SELECT predmeti,
    (ocena1 != '0') + (ocena2 != '0') + (ocena3 != '0') + (ocena4 != '0') + (ocena5 != '0') + (ocena6 != '0') AS prosek_count,
    ocena1 + ocena2 + ocena3 + ocena4 + ocena5 + ocena6 AS prosek
FROM ocene

如果条件表达式为真,则为 1,如果为假,则为 0,您可以将它们相加以获得计数。