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
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'.
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.
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
...
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%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With