MySQL简单的列转行

一个字段有多个状态,统计不同状态下的数据
利用CASE WHEN这种语法实现
列转行的一个简单应用

select
  d.customer_id,
  d.country_code,
  CONVERT(d.create_time, Date) createTime,
  CASE d.send_status WHEN '1' THEN count(d.customer_id) ELSE 0 END AS 'succ',
  CASE d.send_status WHEN '2' THEN count(d.customer_id) ELSE 0 END AS 'fail',
  CASE d.send_status WHEN '3' THEN count(d.customer_id) ELSE 0 END AS 'unknown',
  sum(d.sms_fee) fee
from sms_customer_send_detail d
group by createTime, d.customer_id, d.country_code, d.send_status

结果

+-------------+--------------+------------+------+------+---------+-----+
| customer_id | country_code | createTime | succ | fail | unknown | fee |
+-------------+--------------+------------+------+------+---------+-----+
| hisenyuan   | 65           | 2018-04-08 |   25 |    0 |       0 | 400 |
| hisenyuan   | 65           | 2018-04-08 |    0 |    0 |      10 | 160 |
| hisenyuan   | 86           | 2018-04-08 |    1 |    0 |       0 | 10  |
+-------------+--------------+------------+------+------+---------+-----+

你可能感兴趣的:(MySQL简单的列转行)