MySQL, Oracle, Linux, 软件架构及大数据技术知识分享平台

网站首页 > 精选文章 / 正文

每天一个常用MySQL函数-[case_when_then_end]

2025-02-17 12:24 huorong 精选文章 2 ℃ 0 评论


场景

我们在实现一些类似的统计功能的时候一般会根据场景去分别统计,比如订单存在多种状态我们需要分别统计各种状态的订单,如已支付,待支付,已退款等等,实现方式有多种,这里我们使用sql直接去统计。

语法

CASE expr 
	WHEN condition1 THEN result1 EN
  WHEN condition2 THEN result2 EN
  ELSE result3
END  


如果condition1成立则返回result1 ,否则往下执行,最后到ELse
可以比对下{switch...case...default}

使用

先来看一下订单统计,我们假设3代表已支付、4已退款、0待支付、2已过期
select 
order_status, count(*) 
from tp_order 
group by order_status;
+--------------+----------+
| order_status | count(*) |
+--------------+----------+
|            0 |      876 |
|            1 |        1 |
|            2 |       27 |
|            3 |      467 |
|            4 |       22 |
+--------------+----------+
5 rows in set (0.01 sec)         

--这里也可以用if实现
select order_id as '订单ID', 
  case order_status 
    when 3 then '已支付' 
    when 0 then '待支付' 
    when 4 then '已退款' 
  end as '订单状态' 
from tp_order limit 5;

+----------+--------------+
| 订单ID   | 订单状态     |
+----------+--------------+
|       80 | 已支付       |
|       81 | 已支付       |
|       82 | 已支付       |
|       83 | 已支付       |
|       84 | 已支付       |
+----------+--------------+
5 rows in set (0.00 sec)


select 
sum(case `order_status` when 3 then `order_amount` else 0 end ) as '已支付总金额', 
sum(case `order_status` when 4 then `order_amount` else 0 end ) as '已退款总金 额', 
sum(case `order_status` when 0 then `order_amount` else 0 end ) as '待支付总金额' 
from tp_order;


+--------------------+--------------------+--------------------+
| 已支付总金额       | 已退款总金额       | 待支付总金额       |
+--------------------+--------------------+--------------------+
|        32766777.01 |           29890.41 |         1349925.62 |
+--------------------+--------------------+--------------------+
1 row in set (0.00 sec)

Tags:case when then end

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言