Mysql Crostab查询

时间:2016-10-24 09:24:30

标签: mysql crosstab

存储内容和类别的表很少。内容和类别以多对多关系映射。

一个类别可以有很多内容。

内容可以包含在许多类别中。

因此我创建了content_cat_xref表来映射这些表。

类别表 - id,name等

内容表 - id,name,type_code(read_it,play_it,prove_it,watch_it)

content_cat_xref - content_id,category_id等

我希望显示包含每种内容类型的内容类型和内容数量的类别,如下所示。

enter image description here

但我得到如下。

enter image description here

我的查询如下

select 
ccx.category_id, 
IF(count(c.id) > 0, "True", "False") as Sections_with_content,
(CASE WHEN (c.type_code = 'READ_IT') THEN count(c.id) ELSE 0 END) as "READ_IT",
(CASE WHEN (c.type_code = 'WATCH_IT') THEN count(c.id) ELSE 0 END) as "WATCH_IT",
(CASE WHEN (c.type_code = 'PLAY_IT') THEN count(c.id) ELSE 0 END) as "PLAY_IT",
(CASE WHEN (c.type_code = 'PROVE_IT') THEN count(c.id) ELSE 0 END) as "PROVE_IT",
count(c.id) 
  from content_cat_xref as ccx left outer join content as c
  on ccx.content_id = c.id 
  group by ccx.category_id, c.type_code

如果有人有这种经验将有助于我解决问题。

1 个答案:

答案 0 :(得分:1)

不要按c.type_code分组,因为它会导致各种类型被分组到单独的记录中。条件计数的重点是处理整个整个组(在本例中为category_id)并仅返回相关计数。

更新

您还需要更改条件计数的方式。条件必须在count()(或sum())函数内,而不是在其外部,因为您希望在所有情况下显示结果。所以,而不是

(CASE WHEN (c.type_code = 'READ_IT') THEN count(c.id) ELSE 0 END) as "READ_IT"

COUNT(CASE WHEN (c.type_code = 'READ_IT') THEN 1 ELSE NULL END) as "READ_IT"

说明:如果条件匹配,case语句将返回值1,如果不匹配,则返回nullCount()函数计算所有非空值。根据上面的例子更改所有其他字段的表达式。

相关问题