我需要计算一些列中出现的几个类别的次数。它们像Sports,Medicine这样的字符串,列名是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`
答案 0 :(得分:1)
它会计算所有内容,因为COUNT
会为每个非空值增加其值,而0
不是NULL
。
可能的解决方案:
0
替换为NULL
或使用SUM
代替COUNT
:
SUM(CASE
WHEN ct.category_name = "sports" THEN 1
ELSE 0
end) AS 'sports'
甚至
SUM(ct.category_name = "sports") AS `sports`