1

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

1 回答 1

1

它计算所有内容,因为它会COUNT为每个非空值递增其值,而0不是NULL.

可能的解决方案:

  • 替换0NULLOR
  • 使用SUM代替COUNT

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

甚至

SUM(ct.category_name = "sports") AS `sports`
于 2013-02-14T01:53:58.007 回答