如何在一个查询中执行两次COUNT(*)次提取?

时间:2014-07-18 10:19:30

标签: mysql count

我有一个MySQL表

id | string
------------------------------
 1 | one, two, three
 2 | two, three, five
 3 | one, three, four
 4 | three, five
 5 | one, two, three
 6 | two, three, five
 7 | one, three, four
 8 | one, three, five
 9 | two, three, four, five
10 | one, two, three, five

我希望获取three列中包含子字符串string的元素的比率。我可以轻松地执行两个查询并手动分割:

SELECT COUNT(*) FROM `table` WHERE `string` LIKE '%three%'

并将其除以

SELECT COUNT(*) FROM `table`

但我怎么能只用一个查询来执行此操作呢?

4 个答案:

答案 0 :(得分:1)

您可以将SUM与IF一起使用,在括号内给出1或0: -

SELECT SUM(IF(`string` LIKE '%three%', 1, 0))/COUNT(*)  
FROM `table`

答案 1 :(得分:1)

选择if条件,如果条件为真,则返回1其他明智的0。这里count(*)返回总数或记录。

SELECT (SUM(IF(`string` LIKE '%three%', 1, 0)) * 100)/COUNT(*)  
FROM `table`

答案 2 :(得分:0)

试试这个。

select sum(case when string like '%three%' then 1 else 0 end)/count(*) from table.

答案 3 :(得分:0)

select sum(find_in_set('three', replace(`string`, ' ', '')) > 0) * 100 / count(*) as percentage
from your_table

但你应该考虑改变你的桌面设计。永远不会永远不会在一列中存储多个值!