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

相关推荐
南部余额3 小时前
Canal解决MySQL与Redis数据一致性问题
数据库·redis·mysql·canal·数据·数据同步
Yvonne爱编码4 小时前
JAVA EE初阶---DAY 2 计算机网络
java·开发语言·计算机网络·算法·java-ee·php
斯内普吖5 小时前
(开源)高校素拓分管理系统小程序实战指南 基于 Java + SpringBoot + uni-app + Vue + MySQL
java·spring boot·mysql·小程序·uni-app·开源
zuowei28896 小时前
Laravel 9.x核心特性全解析
php·laravel
Cheng小攸6 小时前
协议分析与分析工具(二)
开发语言·php
lazy H6 小时前
Spring Boot 连接 MySQL 失败怎么办?常见报错原因和解决方法总结
spring boot·后端·学习·mysql·spring
何极光6 小时前
MySQL 8.0详细安装教程(附下载地址)
数据库·mysql·adb
承渊政道6 小时前
【MySQL数据库学习】(MySQL复合查询)
数据库·学习·mysql·bash·database·数据库开发·数据库架构
Cx330❀6 小时前
【MySQL基础】详解MySQL数据类型:底层原理、越界测试与最佳实践
linux·开发语言·数据库·c++·mysql
Leon-Ning Liu6 小时前
MySQL数据恢复实践:binlog2sql数据追加
数据库·mysql