如何计算 SQL 中多列的出现次数
How to count the occurrences in multiple column in SQL
我在 SQL
中有以下 table
TV_Show | genre_1 | genre_2 |
a | action | sci-fi |
b | sci-fi | comedy |
c | comedy | romance |
d | action | sci-fi |
. | . | . |
. | . | . |
. | . | . |
我想要 运行 一个查询,该查询将计算整个 table 中每种不同的、独特的类型出现的次数。我想要以下结果。此输出的顺序无关紧要:
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 table 的简化。我的实际 table 有其他包含不同数据的列。但我只有两个 genre
列,我想对其进行查询。
您可以使用 CASE
表达式和 SUM()
函数; group by
genere
栏喜欢
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
使用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
中有以下 tableTV_Show | genre_1 | genre_2 |
a | action | sci-fi |
b | sci-fi | comedy |
c | comedy | romance |
d | action | sci-fi |
. | . | . |
. | . | . |
. | . | . |
我想要 运行 一个查询,该查询将计算整个 table 中每种不同的、独特的类型出现的次数。我想要以下结果。此输出的顺序无关紧要:
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 table 的简化。我的实际 table 有其他包含不同数据的列。但我只有两个 genre
列,我想对其进行查询。
您可以使用 CASE
表达式和 SUM()
函数; group by
genere
栏喜欢
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
使用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;