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

相关推荐
darkb1rd13 小时前
二、PHP 5.4-7.4版本演进与安全改进
安全·php·webshell
程序 代码狂人13 小时前
CentOS7初始化配置操作
linux·运维·开发语言·php
m0_7482331714 小时前
PHP版本演进:从7.x到8.x全解析
java·开发语言·php
西京刀客14 小时前
MySQL字符集排序规则冲突问题(utf8mb4_unicode_ci和utf8mb4_0900_ai_ci )
mysql·排序·utf8mb4
zhengfei61114 小时前
精选的优秀法证分析工具和资源列表
开发语言·php
橘子1314 小时前
MySQL视图(十二)
数据库·mysql
YIN_尹14 小时前
【MySQL】增删查改的艺术——数据库CRUD完全指南(下)
android·数据库·mysql
zhengfei61115 小时前
踪有趣的 Linux(和 UNIX)恶意软件。提交 PR
java·数据库·mysql
REDcker15 小时前
RFC1918私有IP地址空间详解
网络协议·tcp/ip·php
WangYaolove131415 小时前
基于opencv的疲劳检测系(源码+文档)
python·mysql·django·毕业设计·源码