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

相关推荐
白山云北诗9 分钟前
网站被攻击了怎么办?如何进行DDoS防御?
开发语言·网络安全·php·ddos·防ddos·防cc
真正的醒悟2 小时前
什么是安全设备组网
服务器·数据库·php
赵文宇4 小时前
站在MySQL肩膀上快速入门PostgreSQL,开源社区最喜爱的关系数据库
mysql·postgresql
Gold Steps.4 小时前
数据库正常运行但是端口变成了0?
数据库·mysql
奶茶不甜o5 小时前
php通过身份证号码计算年龄
php
愤怒的苹果ext5 小时前
MySQL JSON查询与索引
mysql·json·虚拟列·多值索引
翻斗花园牛图图-6 小时前
MySQL——库的操作
数据库·mysql
-指短琴长-6 小时前
MySQL快速入门——内置函数
android·数据库·mysql
运维管理8 小时前
Linux系统笔记--Base
开发语言·php
全栈软件开发8 小时前
最新版T5友价互站网源码商城PHP源码交易平台 完整带手机版源码网系统源码
android·开发语言·php