简体   繁体   English

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

[英]select record based on the max value of max occurances and username

The following query works ok: 以下查询可以正常运行:

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 在这里摆弄

I would just like 我只想

A)To get only the most popular category for each username (The one that has the max occurrences) so for the fiddle above for user1 it would be Clothing, Shoes & Accessories (3 occurrences) and for user2 Antiques (3 occurrences), all the other rows in the example apart from those two should be omitted. A)要仅获得每个用户名(出现次数最多的那个)的最受欢迎类别,因此对于上面的用户1小提琴,它将是服装,鞋子和配饰(3次出现),而用户2古董(3次出现)是全部该示例中除这两行以外的其他行均应省略。

B)Another query to get the second most popular category for each username B)另一个查询,以获取每个用户名第二受欢迎的类别

You can use variables to only select the 2 most popular categories per user 您可以使用变量仅为每个用户选择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 http://www.sqlfiddle.com/#!2/ba4ba7/24

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM