mysql如何在1列中计算每个当前值并拆分为3列

时间:2019-02-25 07:06:45

标签: mysql

我的表名是'complain'

+---------------+-------------------+
| date_complain | kategory_complain |
+---------------+-------------------+
| 2019-01-01    | green             |
| 2019-01-01    | green             |
| 2019-01-01    | yellow            |
| 2019-01-02    | yellow            | 
| 2019-01-02    | red               |
+---------------+-------------------+

我要分别计算绿色,黄色和红色,然后按date_complain asc排序

+---------------+-------+--------+-----+
| date_complain | green | yellow | red |
+-------------- +-------+--------+-----+
| 2019-01-01    | 2     | 1      | 0   |
| 2019-01-02    | 0     | 1      | 1   |
+---------------+-------+--------+-----+

我尝试计数,联合及其无效。

1 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

SELECT date_complain, 
       Count(CASE 
               WHEN kategory_complain = 'red' THEN 1 
               ELSE 0 
             END) AS red, 
       Count(CASE 
               WHEN kategory_complain = 'yellow' THEN 1 
               ELSE 0 
             END) AS yellow, 
       Count(CASE 
               WHEN kategory_complain = 'green' THEN 1 
               ELSE 0 
             END) AS green 
FROM   mytable 
GROUP  BY date_complain;