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

相关推荐
shejizuopin1 分钟前
基于JavaSSM+MySQL的实验室考勤管理系统设计与实现
java·mysql·vue·毕业设计·论文·springboot·实验室考勤管理系统设计与实现
alonewolf_9916 分钟前
MySQL全局优化详解与8.0新特性全面解读
数据库·mysql
Full Stack Developme32 分钟前
Mycat 2 实现 MySQL 读写分离,并且实现 主从同步
android·数据库·mysql
BingoGo38 分钟前
免费可商用商业级管理后台 CatchAdmin V5 正式发布 插件化与开发效率的全面提升
vue.js·后端·php
alonewolf_991 小时前
MySQL Explain详解与索引优化实战
数据库·mysql·adb
それども1 小时前
MySQL 查询索引最左前缀原则,如果是(a,b)的联合索引,WHERE b = ? AND a = ?会走索引吗
数据库·mysql
それども1 小时前
MySQL EXPLAIN Impossible WHERE noticed after reading const tables
数据库·mysql
AI 智能服务12 小时前
第6课__本地工具调用(文件操作)
服务器·人工智能·windows·php
萧曵 丶13 小时前
MySQL 主键不推荐使用 UUID 的深层原因
数据库·mysql·索引
松涛和鸣15 小时前
49、智能电源箱项目技术栈解析
服务器·c语言·开发语言·http·html·php