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是运营人员

相关推荐
三道渊35 分钟前
进程通信与网络协议
开发语言·数据库·php
流觞 无依39 分钟前
DedeCMS plus/download.php SQL注入漏洞修复教程
sql·php
爱莉希雅&&&1 小时前
linux中MySQL数据库备份恢复的四种方法(更新中)
linux·数据库·mysql·数据库备份·mysqldumper
Freak嵌入式1 小时前
MicroPython LVGL基础知识和概念:显示与多屏管理
开发语言·python·github·php·gui·lvgl·micropython
枕布响丸辣1 小时前
Python 操作 MySQL 数据库从入门到精通
数据库·python·mysql
Freak嵌入式2 小时前
MicroPython LVGL基础知识和概念:时序与动态效果
开发语言·python·github·php·gui·lvgl·micropython
Java开发追求者2 小时前
windows卸载mysql教程
mysql·mysql卸载
草莓熊Lotso3 小时前
【Linux 线程进阶】进程 vs 线程资源划分 + 线程控制全详解
java·linux·运维·服务器·数据库·c++·mysql
Trouvaille ~3 小时前
【MySQL篇】数据库操作:从创建到管理
linux·数据库·mysql·oracle·xshell·ddl
fengci.4 小时前
php反序列化(复习)(第三章)
android·开发语言·学习·php