我与laravel合作已经超过8个月了,我有一个问题要在表格中显示完成的百分比。所以我的想法是,我要计算一行中不为空的列数,然后除以一行中的列数再乘以100。
类似(NumberOfNotNullColumns/totalNumberOfColumns)*100
但是问题是我无法在选定的行中获取NumberOfNotNullColumns。
$pos_info = DB::select(DB::raw('SHOW COLUMNS FROM resource'));
$pos_info_act = DB::select(DB::raw('SELECT count(*) from resource WHERE * IS NOT NULL AND user_id = '.$resource->user_id));
foreach ($pos_info as $item) $base_columns += 1;
$percentage = ($pos_info_act/$pos_info)*100;
如您所见,MySQL经验不足
答案 0 :(得分:2)
您可以尝试以下查询,
select (sum(case when column is not null then 1 else 0 end)/sum(case when column is null then 1 else 0 end))*100 from tableName
答案 1 :(得分:0)
使用模型查询
$all = Resource::count();
$notNull = Resource::whereNotNull('your_field_name')->count();
$percent = ($notNull/$all)*100;
print_r($percent);
exit;
使用数据库查询
$all = DB::table('resource')->count();
$notNull = DB::table('resource')->whereNotNull('your_field_name')->count();
$percent = ($notNull/$all)*100;
print_r($percent);
exit;
您需要指定一个为空或不为空的列
答案 2 :(得分:0)
万一有兴趣的人,这就是我最终要做的方式
private function complete_percentage($model, $table_name, $resource){
$pos_info = DB::select(DB::raw('SHOW COLUMNS FROM '.$table_name));
$base_columns = count($pos_info);
$not_null = 0;
foreach ($pos_info as $col){
$not_null += app('App\\'.$model)::selectRaw('SUM(CASE WHEN '.$col->Field.' IS NOT NULL THEN 1 ELSE 0 END) AS not_null')->where('user_id', '=', $resource->user_id)->first()->not_null;
}
return ($not_null/$base_columns)*100;
}
答案 3 :(得分:0)
如果有人对 PD 感兴趣:抱歉我会说西班牙语,请使用英语翻译器。
在 Lavarel 6 中测试
//consulting specific user
$user = User::find(Auth::id());
//counters
$contadornull = 0;
$cantidadcampos = 0;
// using $user->getFillable() for return all fields the model
foreach ($user->getFillable() as $key => $campos) {
//exclude data were user not filliables
if($campos != 'fotografia' && $campos != 'rango' && $campos != 'password' &&
$campos != 'estatus')
{
//count all fields
$cantidadcampos = $cantidadcampos + 1;
//count fields where value is null
if($user->$campos != null)
{
$contadornull++;
}
}
}
//calculate percentage
$porcentaje = $contadornull / $cantidadcampos * 100;