统一不同的字段并获得更多重复值

时间:2016-02-24 08:36:03

标签: sql union

我有一个包含相同字段的不同列的表格,如:

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

我怎样才能获得前五种类型(考虑两列)? 我认为一个好的方法是得到类似的东西:

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,但我不知道如何)。

谢谢

3 个答案:

答案 0 :(得分:0)

尝试使用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;

答案 1 :(得分:0)

试试这个:

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;

答案 2 :(得分:0)

像这样使用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;