时间:2021-07-01 10:21:17 帮助过:18人阅读
简单函数:
CASE [col_name] WHEN [value1] THEN [result1]…ELSE [default] END;枚举这个字段所有可能的值。
SELECT DATE_FORMAT( paytime, ‘%Y-%m-%d-%H‘ ) payhours, state, CASE state WHEN ‘1‘ THEN ‘交易成功‘ WHEN ‘2‘ THEN ‘交易失败‘ WHEN ‘0‘ THEN ‘待支付‘ ELSE ‘无‘ END ‘状态名称‘ FROM payorder WHERE DATE_FORMAT( paytime, ‘%Y-%m-%d‘ ) = ‘2020-05-26‘ GROUP BY payhours ASC;
查询结果:
搜索函数:
CASE WHEN [expr] THEN [result1]…ELSE [default] END;搜索函数可以写判断,并且搜索函数只会返回第一个符合条件的值,其他case
被忽略.即:在when后面的表达式中写出要搜索的判断条件,然后在THEN后面写上判断结果。
SELECT DATE_FORMAT( paytime, ‘%Y-%m-%d-%H‘ ) payhours, CASE WHEN paytime <=‘2020-05-26 09:00:00‘ THEN ‘早上‘ WHEN paytime <=‘2020-05-26 12:59:59‘ THEN ‘上午‘ ELSE ‘下午‘ END ‘时间段‘ FROM payorder WHERE DATE_FORMAT( paytime, ‘%Y-%m-%d‘ ) = ‘2020-05-26‘ GROUP BY payhours ASC;
查询结果:
聚合函数 sum 配合 case when 的简单函数实现行转列
SELECT DATE_FORMAT( paytime, ‘%Y-%m-%d-%H‘ ) payhours, sum( CASE state WHEN ‘1‘ THEN 1 ELSE 0 END ) AS state1, sum( CASE state WHEN ‘2‘ THEN 1 ELSE 0 END ) AS state2, sum( CASE state WHEN ‘0‘ THEN 1 ELSE 0 END ) AS state0 , count(payorderid) AS countsum FROM payorder WHERE DATE_FORMAT( paytime, ‘%Y-%m-%d‘ ) = ‘2020-05-26‘ GROUP BY payhours ASC;
MySQL: case when 用法
标签:并且 default 简洁 com 结果 sum info 表达式 form