[英]mysql count occurrence of a string
我需要计算几个类别出现在一列中的次数。 它们存储为“体育”,“医学”之类的字符串,列名称为ct.category_name。
这是我正在适应的查询。 我想要每个类别类型的列。
select co.order_id, co.catalog_item_id, ct.category_name
from customer_order as co
join item_category as ic on (ic.item_id = co.customer_id )
join category_translations as ct on (ct.category_id = ic.category_id)
where co.paid = 1 and co.customer_id = 22500 and ct.locale = "en"
当我将它放在select语句中时,它计算了所有内容,我可以理解为什么,但是我不确定该朝哪个方向前进。
count(CASE
WHEN ct.category_name = "sports" THEN ct.category_name
ELSE 0
end) AS 'sports'
再次,我希望每个字符串的计数成为其自己的列。 任何帮助将非常感激。
当我尝试:
select co.order_id, co.catalog_item_id, ct.category_name
, SUM(ct.category_name = "sports") AS `sports`
, SUM(ct.category_name = "medici") AS `medicine`
from customer_order as co
join item_category as ic on (ic.item_id = co.customer_id )
join category_translations as ct on (ct.category_id = ic.category_id)
where co.paid = 1 and co.customer_id = 22500 and ct.locale = "en"
它两次计数运动。 什么时候放错地方了? 结果:
`23115 271708 sports 483 483`
它计数所有内容,因为COUNT
为每个非null值递增其值,并且0
不为NULL
。
可能的解决方案:
NULL
替换0
或 使用SUM
而不是COUNT
:
SUM(CASE WHEN ct.category_name = "sports" THEN 1 ELSE 0 end) AS 'sports'
甚至
SUM(ct.category_name = "sports") AS `sports`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.