mysql 分组按条件统计

时间:2023-03-08 16:18:07

百度经验

COUNT(CASE WHEN (S.rank = 1) THEN S.loanContractId END ) AS 'MZ',  //根据loanContractId 分组,并统计rank=1出现的次数

CI 框架

/**
* 获取三种消息类型各自的未读数
* @param int $user_id 用户的id
* */
public function get_unread_count($user_id) {
$this->db->select('COUNT( CASE WHEN push_type=1 THEN 1 ELSE NULL END ) AS `remind_count`,COUNT( CASE WHEN push_type=2 THEN 1 ELSE NULL END ) AS `appoint_count`,COUNT( CASE WHEN push_type=3 THEN 1 ELSE NULL END ) AS `medical_count`');//查询一个字段三种状态的数量
$this->db->where('user_id', $user_id);//条件
$this->db->where('is_read', 0);//条件
$query = $this->db->get('common_push');//表名
$data = $query->row_object();
return $data;
}