Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count multiple CASE occurrences in SQL

Tags:

sql

mysql

I'm looking for solution for the following issue:

SELECT CASE WHEN p.value LIKE '%foo%' THEN 'foos'
    WHEN p.value LIKE '%bar%' THEN 'bars'
    WHEN p.value LIKE '%bakar%' THEN 'bakars'
    ELSE p.value END as value,
COUNT(*) as count FROM table_a p GROUP BY value

Values are something like:

foo, bar, foo and bar, bakar, bakarbar, foobar

Result of this query is:

 value    count
 foos       3
 bars       2
 bakars     1

This code successfully counts occurrences, but the CASE stops at first match. Is there a way to do this?

value    count
 foos       3
 bars       4
 bakars     2
like image 646
Kadel Avatar asked Dec 15 '16 10:12

Kadel


People also ask

How do I count number of occurrences in SQL?

COUNT(ID) as NumberOfOccurance:- Counting the number of occurrence of a ID. group by – It is necessary in aggregate function like 'count()' otherwise it will give error. having (COUNT(ID)>1) -Select those rows which count of ID value is greater than 1, that's why it shows '0' and '1'.

Can you use count and case SQL?

The function Countifs can often be implemented with an and condition in the case expression. The function counta can be implemented with a case expression as well. For that, SQL makes a distinction between empty strings and the null value.


2 Answers

In a single case expression no, you cannot achieve what you want precisely because case stops at the first match.

You need to have separate case expressions or if() function calls to achieve the expected outcome. If you do not mind having the results in different columns, then use conditional counting:

select count(if(p.value LIKE '%foo%',1,null)) as foos,
       ...
from table_a p

If you insist on receiving the counts in the same column, then use union:

select 'foos' as `value`, count(*) from table_a where table_a.value LIKE '%foo%'
union
...
like image 177
Shadow Avatar answered Sep 22 '22 11:09

Shadow


You can use UNION if you want to count more than 1 occurrence in each string:

SELECT 'foos' as value, count(*)
FROM YourTable
WHERE p.value LIKE '%foo%'
UNION ALL
SELECT 'bars' as value, count(*)
FROM YourTable
WHERE p.value LIKE '%bar%'
UNION ALL
SELECT 'bakars' as value, count(*)
FROM YourTable
WHERE p.value LIKE '%bakar%'
like image 45
sagi Avatar answered Sep 22 '22 11:09

sagi