首页 > 解决方案 > 如何计算具有垂直值的多列?

问题描述

我是编程新手。我有桌子

check_1,check_2,check_3 ..etc
------------------------------
 1       1       1
 0       0       1
 1       0       1

我想要这个输出:

column_name, count_true
-----------------------
  check_1       2
  check_2       1
  check_3       3

我已经使用 union 函数尝试了 mysql,但是当我尝试在 laravel 中应用它时,我遇到了 union 问题。是否有无联合查询可以产生这样的输出?

提前致谢

标签: mysqllaravel

解决方案


你可以这样做。数据库中的一个查询

$records = DB::table('your_table')->get();
$check1Count = $records->where('check_1', 1)->count();
$check2Count = $records->where('check_2', 1)->count();
$check3Count = $records->where('check_3', 1)->count();
......

或者

$records = DB::table('your_table')->get();
$columns = ['check_1', 'check_2', 'check_3', ...];
$data = [];
foreach($columns as $column) {
    $data[] = [
        'column_name' => $column,
        'count_true' => $records->where($column, 1)->count();
    ];
}

您也可以这样做,但查询很多

$check1Count = DB::table('your_table')
    ->selectRaw('COUNT(check_1) as count')
    ->where('check_1', 1)
    ->first()
    ->count;

$check2Count = DB::table('your_table')
    ->selectRaw('COUNT(check_2) as count')
    ->where('check_2', 1)
    ->first()
    ->count;
.....

推荐阅读