ThinkPHP 5 根据账户类型的不同统计数据中使用CASE WHEN THEN SQL语句实例

项目场景

是外卖代运营平台,每个客户都有相关运营人员、签约业务员,分别在客户信息表里有user_id、business_id字段记录。

需求描述

在网站用户列表里,能直观看到实际每个人所关联的客户总数量、不同状态的数量分别是多少。

解决方案
php 复制代码
$res_arr = User::alias('a')
            ->field('
            a.*,
            l.name as level_name,
            (SELECT COUNT(*) AS tp_count FROM `qqxz_shop_customer` where a.id=user_id and `delete_time` is  null) shop_sum,
            (SELECT COUNT(*) AS tp_count FROM `qqxz_shop_customer` where a.id=business_id and `delete_time` is  null) business_sum,
            (SELECT COUNT(*) AS tp_count FROM `qqxz_shop_customer` where a.id=(CASE WHEN user_type = 2 THEN user_id ELSE business_id END )  and `delete_time` is  null and operation_status=4) contract_sum,
            (SELECT COUNT(*) AS tp_count FROM `qqxz_shop_customer` where a.id=(CASE WHEN user_type = 2 THEN user_id ELSE business_id END )  and `delete_time` is  null and operation_status=3) stop_sum,    
            (SELECT COUNT(*) AS tp_count FROM `qqxz_shop_customer` where a.id=(CASE WHEN user_type = 2 THEN user_id ELSE business_id END )  and `delete_time` is  null and operation_status=1) ing_sum,
            (SELECT COUNT(*) AS tp_count FROM `qqxz_shop_customer` where a.id=(CASE WHEN user_type = 2 THEN user_id ELSE business_id END )  and `delete_time` is  null and operation_status=2) wait_sum
            ')
            ->join('qqxz_user_level l','l.id = a.level','left')
            ->where('a.user_type!=1')
            ->where('a.delete_time',null)
            ->order('a.create_time desc')
            ->where($sql)
            ->paginate($limit, $simple = false,['page'=>$page])
            ->toArray();

user_type 2是运营人员

相关推荐
冻咸鱼18 小时前
数据库操作
数据库·mysql·数据库操作
、花无将18 小时前
PHP:配置问题从而导致代码运行出现错误
开发语言·php
duqiao_wang18 小时前
Mysql数据库系统库数据恢复
数据库·mysql
zorro_z19 小时前
ThinkPHP8学习篇(九):模型(一)
php
计算机学姐19 小时前
基于微信小程序的垃圾分类管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
Albert Edison1 天前
【MySQL】数据类型
数据库·mysql·adb·oracle
遇见火星1 天前
MYSQL-物理备份(xtrabackup)使用指南
数据库·mysql·adb
huihuihuanhuan.xin1 天前
后端八股之mysql
数据库·mysql
洋不写bug1 天前
数据库数据类型,数据值类型,字符串类型,日期类型详解
数据库·mysql
打酱油的;1 天前
【无标题】
爬虫·python·php