基于like语句和Group by的SQL计数

问题描述

我有一个类似于以下结构的表。我需要根据MessageValue列的值获取失败,成功和部分成功的计数。如果Messagevale列包含“失败”,则为“失败”,将“成功”视为成功,将“部分成功”视为部分失败。因此,我需要检查计数内的LIKE标准,并且我还需要根据日期进行检查。我尝试使用Count with Group by进行尝试,但没有得到我所需要的。

Date                   MessageValue
-----------------------------------------------
10/18/2020             Process Failed some text here
10/18/2020             Process success some text here
10/19/2020             Partial success some text here
10/19/2020             Process Failed some text here
10/19/2020             Process Failed some text here
10/19/2020             Process partial success some text here
10/20/2020             Process partial success some text here
------------------------------------------------

所以输出应如下所示。

Date                   Success      Failure     Partial Failure
-----------------------------------------------------------------
10/18/2020               1             1            0
10/19/2020               1             2            1
10/20/2020               0             0            1

解决方法

您可以在like条件下进行条件聚合。这似乎可以满足您的要求:

select
    date,sum(case when col like '%success%' and col not like '%partial success%' then 1 else 0 end) success,sum(case when col like '%failed%' then 1 else 0 end) failure,sum(case when col like '%partial failed%' then 1 else 0 end) partial_success
from mytable
group by date