Domanda

I'm trying to get the AVG() and the STDDEV_SAMP() on subset of data using Laravel.

So I've tried

//Data from which I want to calculate the AVG and STDDEV_SAMP()
//Limit the query to certain values
$subquery = TableAModel::join('TableB','TableA.TableB_id','=','TableB.id')
                                ->select('Factor1')
                                ->whereraw('conditionA <= 10')
                                ->orderBy('DateTimeCode', 'desc')
                                ->take('5')
                                ->toSql();

//My aggregate functions     
    $aggregates = 'AVG(TableA.Factor1) as Factor1,
                        STDDEV_SAMP(TableA.Factor1) as Factor1_SD';
//My final query that should return the average and SD                                
    $AVG_SD = \DB::table(\DB::raw(" ($subquery) as sub "))->select(\DB::raw("$aggregates"))->first()->toArray();

//it should return something like array([Factor1] => The_average, [Factor1_SD] => The_SD)

However, it throws me "Column not found: 1054 Unknown column 'TableA.Factor1' in 'field list'". If I try to select('*'), it throws me "Duplicate columns id".

È stato utile?

Soluzione

I don't really have any experience with this but, it looks to me like your creating a view and from that view you want to find the STD and AVG of Factor1. But you say AVG(TableA.Factor1) as Factor1, I don't think TableA would be the table name for DB::table(\DB::raw(" ($subquery) as sub ")) so its not finding Factor1 because its can't find the table. would the table not be called sub.

I have no idea if this is the case or not, but hope it helps, also would've left a comment but I don't have the rep yet :(.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top