[英]How to count the occurrences in multiple column in SQL
我在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 Query應該是什么?
編輯我已經嘗試運行以下命令,但它不起作用:
SELECT genre1 OR genre2, COUNT(*) FROM tv_show GROUP BY genre1 OR genre2
編輯2
這個例子簡化了我的實際SQL表。 我的實際表有其他列有不同的數據。 但我只有兩個genre
列,我想進行查詢。
使用union all
和aggregation:
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;
您可以使用CASE
表達式和SUM()
函數; group by
genere
列group by
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.