0

I want to count the occurrences of a string within the column "diagnosis".

What I am doing now is simply this - it gets my needed results

SELECT COUNT(*), diagnosis
FROM patients
WHERE diagnosis like "%OS1%"
UNION

SELECT COUNT(*), diagnosis
FROM patients
WHERE diagnosis like "%OS2%"

... and so on

Sometimes in my table the strings can occur twice (e.g. OS1, OS2), I want to count every single occurence of the strings.

I think it would be a pretty easy task in another language but I want to do it in pure SQL.

3
  • How to know which OS1, OS2 etc values to search for? Commented Jun 4, 2018 at 7:43
  • The strings are limited to OS1-OS6 and CH1-CH6 Commented Jun 4, 2018 at 7:48
  • Put those values in a separate (temporary?) table and join with it! Commented Jun 4, 2018 at 7:50

4 Answers 4

2

Put the OS1-OS6 and CH1-CH6 values in a diagn table. JOIN and GROUP BY:

SELECT COUNT(*), d.diagnosis
FROM patients p
RIGHT JOIN diagn d
   on p.diagnosis like concat('%', d.diagnosis, '%')
group by d.diagnosis
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT sum(OS1) as OS1_total, sum(OS2) as OS2_total, sum(OS3) as OS3_total,
sum(OS4) as OS4_total, sum(OS5) as OS5_total, sum(OS6) as OS6_total, 
sum(CH1) as CH1_total, sum(CH2) as CH2_total, sum(CH3) as CH3_total,
sum(CH4) as CH4_total, sum(CH5) as CH5_total, sum(CH6) as CH6_total
FROM
(
SELECT (case when diagnosis like '%OS1%' then 1 else 0 end) as OS1,
(case when diagnosis like '%OS2%' then 1 else 0 end) as OS2,
(case when diagnosis like '%OS3%' then 1 else 0 end) as OS3,
(case when diagnosis like '%OS4%' then 1 else 0 end) as OS4,
(case when diagnosis like '%OS5%' then 1 else 0 end) as OS5,
(case when diagnosis like '%OS6%' then 1 else 0 end) as OS6,
(case when diagnosis like '%CH1%' then 1 else 0 end) as CH1,
(case when diagnosis like '%CH2%' then 1 else 0 end) as CH2,
(case when diagnosis like '%CH3%' then 1 else 0 end) as CH3,
(case when diagnosis like '%CH4%' then 1 else 0 end) as CH4,
(case when diagnosis like '%CH5%' then 1 else 0 end) as CH5,
(case when diagnosis like '%CH6%' then 1 else 0 end) as CH6
FROM patients
) as mytable

2 Comments

That one fixed it! Thanks a lot!
If you find the answer useful, please mark it as useful by clicking the up arrow.
0

You can try this also:

SELECT COUNT(*), diagnosis
FROM patients
GROUP BY diagnosis;

Comments

0

Not sure if this works.

SELECT COUNT(*) 
FROM patients 
WHERE REGEXP_LIKE(diagnosis, "(OS[1-6]|CH[1-6])")

You may also check out link below if you're interested. Not sure if it's what you're looking for though:
https://dev.mysql.com/doc/refman/8.0/en/regexp.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.