如果我的问题看起来很明显,我对SQL很陌生
我想计算列#34;诊断"中字符串的出现次数。
我现在正在做的只是这个 - 它得到我需要的结果
SELECT COUNT(*), diagnosis
FROM patients
WHERE diagnosis like "%OS1%"
UNION
SELECT COUNT(*), diagnosis
FROM patients
WHERE diagnosis like "%OS2%"
... and so on
有时在我的表中,字符串可以出现两次(例如OS1,OS2),我想计算每一个字符串的出现次数。
我认为在另一种语言中这将是一项非常简单的任务,但我想在纯SQL中完成它。
你对我有什么建议吗?
答案 0 :(得分:2)
将OS1-OS6和CH1-CH6值放入诊断表中。 JOIN
和GROUP BY
:
SELECT COUNT(*), d.diagnosis
FROM patients p
RIGHT JOIN diagn d
on p.diagnosis like concat('%', d.diagnosis, '%')
group by d.diagnosis
答案 1 :(得分: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 :(得分:0)
你也可以试试这个:
SELECT COUNT(*), diagnosis
FROM patients
GROUP BY diagnosis;
答案 3 :(得分:0)
不确定这是否有效。
SELECT COUNT(*)
FROM patients
WHERE REGEXP_LIKE(diagnosis, "(OS[1-6]|CH[1-6])")
如果您有兴趣,也可以查看下面的链接。不确定它是否是您正在寻找的东西:
https://dev.mysql.com/doc/refman/8.0/en/regexp.html