Sum rows of a Table

Hi i’m new with Yii2

I’m trying to sum some fields of a same row, not column, a row.

how could I do this in yii 2 ?

this is a view of my table evaluation

ID idpro idclass idprof idstud userd p1 p2 p3 p4 p5 p6 p7 p8 p9 average


14 2 6 10 35 can 10 8 0 0 0 0 2 0 5 NULL

I need to sum the values between column P1 and P9 and make the average of the sum. But the average must be calculated considering only the values greater than zero.

Thanks by the help!

Create a getter method in your model that calculates the average. For example:




public function getAverage()

{

    $sum = 0;

    $count = 0;


    if ($this->p1 > 0) {

        $sum += $this->p1;

        $count++;

    }

    if ($this->p2 > 0) {

        $sum += $this->p2;

        $count++;

    }

    ...


    if ($count > 0) {

        return (double)$sum / $count;

    } else {

        return 0;

    }

}



Then you can use ‘average’ attribute through this getter method.

Amazing !! Thanks [color="#2B3730"][size="2"]softark[/size][/color]