How to count occurrences in multiple columns in SQL

I have the following table in SQL

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

I want to run a query that will count the number of times each of different unique genres appears in the whole table. I want to get the following result. The order of this output does not matter:

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

What should be the SQL query?

Edit I have already tried running the following, but it does not work:

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

Edit 2

This example simplifies my actual SQL table. There are other columns with different data in my actual table. But I have only two columns genrefor which I want to execute a query.

+4
source share
2 answers

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;
+4

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
+1

Source: https://habr.com/ru/post/1664431/


All Articles