sql中的case when 用法

535 阅读1分钟

这几天学到了sql中的case when语句, 记录如下:

mysql> select sum(case when task_id>20 then 2 end) from a_sync_task_yiguan;
+--------------------------------------+
| sum(case when task_id>20 then 2 end) |
+--------------------------------------+
|                                   16 |
+--------------------------------------+
1 row in set (0.01 sec)

mysql> select sum(case when task_id>20 then 1 end) from a_sync_task_yiguan;
+--------------------------------------+
| sum(case when task_id>20 then 1 end) |
+--------------------------------------+
|                                    8 |
+--------------------------------------+
1 row in set (0.02 sec)
select count(case when task_id=56 then 2 end) from a_sync_task_yiguan;
+----------------------------------------+
| count(case when task_id=56 then 2 end) |
+----------------------------------------+
|                                      1 |
+----------------------------------------+
1 row in set (0.04 sec)