2013-02-14 32 views
1

我需要计算几个类别在列中出现的次数。他们被认为是体育,医学等字符串,栏目名称是ct.category_name。mysql计数出现的字符串

这是我正在适应的查询。我想为每个类别类型添加一列。

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` 

回答

1

它计算一切,因为COUNT增加它的价值对每个不为空值,0NULL

可能的解决方案:

  • 更换0NULL
  • 使用SUM,而不是COUNT

    SUM(CASE 
    WHEN ct.category_name = "sports" THEN 1 
    ELSE 0 
    end) AS 'sports' 
    

甚至

SUM(ct.category_name = "sports") AS `sports` 
+0

Coo,但是当我适应第二个字符串时,它只计算第一个字符串,然后重复它。如果这不是在选择? – jahrichie 2013-02-14 02:00:00

+0

@jahrichie:我不确定我了解你。显示你的确切代码,猜测不是解决编程问题的最佳方法 – zerkms 2013-02-14 02:26:17

+0

我用我的尝试和结果更新了第一篇文章。在此先感谢 – jahrichie 2013-02-14 02:39:00