统一不同字段,获取top更多重复值

Unify different fields and get top more repeated values

我有一个 table 具有相同字段的不同列,例如:

  ID |  Genre1  |   Genre2   
  1  |  Sci-fi  |   Drama
  2  |  Musical |   Sci-fi

我怎样才能获得前 5 名的流派(考虑到两列)? 我认为一个好的方法是:

Genre      Count 
Sci-fi       13            
Drama        11            

然后我会用"TOP"。

现在我正在使用:

SELECT TOP 5 Genre1, count(Genre1) AS times
FROM Customer_Profile
GROUP BY Genre1
ORDER BY count(Genre1) DESC;

它适用于其中一个列,但我如何应用它才能同时考虑两个类型列? (我可能需要使用 Union All 但我不知道如何使用)。

谢谢

试试 union all

SELECT TOP 5 Genre, count(Genre) AS times
FROM (
    select Genre1 Genre
    from Customer_Profile
    union all
    select Genre2 Genre
    from Customer_Profile
) x
GROUP BY Genre
ORDER BY count(Genre) DESC;

试试这个:

SELECT genre,
       COUNT(*)
FROM
(SELECT genre1 AS genre
 FROM   Customer_Profile
 UNION ALL
 SELECT genre2 AS genre
 FROM   Customer_Profile
)
GROUP BY genre
ORDER BY 2;

像这样使用 UNION:

SELECT TOP 5 Genre,count(Genre) as Times
FROM(select Genre1 as Genre FROM Customer_Profile
     UNION ALL
     select Genre2 FROM Customer_Profile)
GROUP BY Genre
ORDER BY count(Genre) DESC;