mysql - 如何计算具有垂直值的多列?
问题描述
我是编程新手。我有桌子
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 问题。是否有无联合查询可以产生这样的输出?
提前致谢
解决方案
你可以这样做。数据库中的一个查询
$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;
.....
推荐阅读
- r - 估计“R”中混合效应逻辑回归中的风险比而不是优势比
- elasticsearch - 如何在弹性搜索中获得同义词匹配的自动建议
- ubuntu - 创建我当前机器/设置的 VDI
- java - ReentrantLock 和 Condition 中处于等待状态的线程如何维护和区别?
- micropython - 使用带有伺服电机的 bbc-microbit v2 时出错
- javascript - jquery与angularjs冲突
- c - 我正在尝试让我的 printf 从我的 Char 内部进行格式化
- php - 单击时在 Jquery 中发布数据表
- python - python selnium网站登录除了问题
- python - 如何在每次迭代中使用不同的函数