I want to get the total occurrence of values in a list. See the raw Data:
In Laravel, see the code i have written but it is not correct, so i need assistance:
public static function ServiceNo($service,$fltno,$type)
{
$res = DB::table('tbname')
->select(DB::raw('count(distinct(nextSvr)) as svr'))
->where(['fltno'=>$fltno,'mtype'=>$type,'serviceType'=>$service])
->get();
foreach($res as $r){
$cnn = $r->svr;
}
return $cnn;
}
The above code, will only count the distinct nextsvr, however,what i want is better explained like this: from the above, the first three 7's are counted as 1, the next three series is 1, etc, at the end total count for service type A will be 9 services. Please, i need help in this regard.
You should try below example
$count = DB::table('tablename')->count(DB::raw('DISTINCT name'));
OR
DB::table('tablename')->distinct('name')->count('name');
Try this.
In MySQL it would be:
SET @prev := 0;
SELECT sum(col) as distinct_count
FROM (
SELECT *, if(@prev = nextSvr, 0, 1) as col,
@prev := nextSvr
FROM tbname
) x
By using a variable I think you can look out for changes between rows and increment a counter accordingly. So if the row changes add 1.
You could translate this into eloquent and use it:
DB::statement(DB::raw('SET @prev := 0'));
$count = DB::select(DB::raw("
SELECT sum(col) as distinct_count
FROM (
SELECT *, if(@prev = nextSvr, 0, 1) as col,
@prev := nextSvr
FROM tbname
) x
"))
Are you looking for something like this, perhaps?
public function countServices(Request $request)
{
$counter = 0;
$fltno = '';
$foo = DB::table('bar')
->where([
['fltno', '=', $request->fltno],
['mType', '=', $request->type],
['serviceType', '=', $request->service]
])
->get();
foreach( $foo as $bar )
{
if( $fltno != $bar->fltno )
{
$fltno = $request->fltno;
$counter++;
}
}
return $counter;
}