我需要计算几个类别在列中出现的次数。它们存储为 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`