根据最大出现次数和用户名的最大值选择记录

时间:2014-09-22 16:53:55

标签: mysql

以下查询正常:

SELECT user.username, preference.user_id, preference.category,COUNT(*) AS occurrences 
  FROM preference inner 
  JOIN user on preference.user_id=user.userid
 where category is not null and category!=""
 GROUP BY category,user_id 
 ORDER BY occurrences DESC ;

fiddle here

我想要

A)只获得每个用户名的最受欢迎的类别(具有最大出现次数的用户名),因此对于user1的上述小提琴,它将是服装,鞋子&附件(3次出现)和用户2古董(3次出现),除了这两个之外的所有其他行都应该省略。

B)另一个查询,以获得每个用户名的第二个最受欢迎的类别

1 个答案:

答案 0 :(得分:2)

您可以使用变量仅为每个用户选择2个最受欢迎的类别

SELECT * FROM (
    SELECT * ,
    @rowNum := IF(@prevUserId = user_id,@rowNum+1,1) rowNum,
    @prevUserId := user_id
    FROM (
        SELECT user.username,@prevUserId,preference.user_id, category, COUNT(*) AS occurrences
        FROM preference inner JOIN user 
        on preference.user_id=user.userid
        where category is not null and category!=""
        GROUP BY category,preference.user_id
    ) t1 order by user_id, occurrences desc
) t1 WHERE rowNum <= 2

http://www.sqlfiddle.com/#!2/ba4ba7/24