【问题标题】:How to count the occurrences in multiple column in SQL如何计算SQL中多列中的出现次数
【发布时间】:2016-12-21 13:33:23
【问题描述】:

我在 SQL 中有下表

TV_Show | genre_1 | genre_2 |
  a     | action  | sci-fi  |
  b     | sci-fi  | comedy  |
  c     | comedy  | romance |
  d     | action  | sci-fi  |
  .     |    .    |    .    |
  .     |    .    |    .    |
  .     |    .    |    .    |

我想运行一个查询来计算每个不同的、独特的流派在整个表中出现的次数。我想要以下结果。此输出的顺序无关紧要:

action    2
sci-fi    3
comedy    2
romance   1
  .       .
  .       .
  .       .

SQL 查询应该是什么?

编辑 我已经尝试运行以下命令,但它不起作用:

SELECT genre1 OR genre2, COUNT(*) FROM tv_show GROUP BY genre1 OR genre2

编辑 2

这个例子是对我的实际 SQL 表的简化。我的实际表有其他具有不同数据的列。但我只有两个 genre 列,我想对其进行查询。

【问题讨论】:

  • @Viki888,检查我的编辑

标签: mysql sql count multiple-columns


【解决方案1】:

使用union all 和聚合:

select genre, count(*)
from ((select genre_1 as genre from tv_show) union all
      (select genre_2 as genre from tv_show)
     ) g
group by genre;

通过简单的修改,您可以为每一列添加计数:

select genre, count(*), sum(first), sum(second)
from ((select genre_1 as genre, 1 as first, 0 as second from tv_show) union all
      (select genre_2 as genre, 0, 1 from tv_show)
     ) g
group by genre;

【讨论】:

  • 您好,我是 SQL 新手,请您解释一下 't' 和 'g' 是什么?
  • @TrackFry 。 . . g 是表别名,from 子句中的派生表需要。
  • 对不起,在这种情况下我的表别名是什么?我不确定你的意思。
  • g 命名前面的from (...)。 SQL 要求您在此处提供一个(临时的、新的)名称
  • @GordonLinoff 你在这里写的genre 是什么?这是表的名字吗? tv_show 也一样,这是指我的表名吗?
【解决方案2】:

您可以将CASE 表达式与SUM() 函数一起使用; group bygenere 列赞

sum(case when genre_1 = 'action' then 1 else 0 end) as Action,
sum(case when genre_1 = 'sci-fi' then 1 else 0 end) as Sci-Fi,
sum(case when genre_1 = 'comedy' then 1 else 0 end) as Comedy,
sum(case when genre_1 = 'romance' then 1 else 0 end) as Romance

【讨论】:

  • 我必须对每个流派一个一个地进行这个查询吗?另外,你可以给我看看输出吗?
  • @TrackFry,如果您想按流派类型计数,那么是的,您必须这样做。输出将与您在问题中发布的内容相同。
  • 我刚试过,但没用。我给出的例子是我的表格的简化。在我的实际表中,我有更多包含其他数据的列。但我只有两个genre 列。我需要改变什么才能让它工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
相关资源
最近更新 更多