这是一个非常相似的问题的链接,除了在他们的示例中他们只关注一个专栏,而我将关注多个专栏。 SQL Select most common values
这是我的问题:
我需要显示电子邮件地址、用户留下的评论数,并显示与每封电子邮件关联的最常用用户名。我已经完成了前两个步骤;即我让它显示电子邮件以及评论数量。现在客户想要最常用的用户名。
这里是获取我上面提到的电子邮件和评论数的查询。
select comment_author_email, count(*) from wp_comments group by comment_author_email order by count(*) desc
现在我的任务是让最常用的用户名显示在第三列中。
例如:
email | username | comment
------------------------------
1@test | one | blah..
1@test | ONE | blah..
1@test | one | blah..
2@test | TWO | blah..
2@test | TWO | blah..
3@test | tre | blah..
我希望作为输出
email |numComments| mostCommonName
------------------------------------
1@test | 3 | one
2@test | 2 | TWO
3@test | 1 | tre
最佳答案
这是使用 group_concat()
/substring_index()
技巧的好地方。但这需要一个子查询。
select comment_author_email, sum(cnt),
substring_index(group_concat(username order by cnt desc), ',', 1) as MostCommonName
from (select comment_author_email, username, count(*) as cnt
from wp_comments
group by comment_author_email, username
) cu
group by comment_author_email
order by sum(cnt) desc;
关于mysql - SQL:电子邮件的最常出现的用户名,按电子邮件中的大多数条目排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24666584/