表名:d_risposte id:index,唯一不相关 回复:从1到4
id | reply | user
-----------------
| 1 | a34
| 2 | a34
| 1 | a34
| 3 | a34
| 2 | a34
| 4 | a34
| 1 | a34
| 1 | a34
| 4 | a55
| 2 | a55
| 2 | a55
| 4 | a71
| 4 | a71
| 1 | a71
| 3 | a71
| 4 | a71
| 2 | a71
| 4 | a71
| 4 | a71
| 2 | b22
| 4 | b22
| 2 | b22
我希望只保留以“a”开头且至少有7条回复的用户, 然后 我希望计算大多数重播1..4在这种情况下结果应该是:
user | top_reply
----------------
a34 | 1 (becouse the 1 reply appears 4 times)
a71 | 4 (becouse the 4 reply appears 5 times)
(如果它是平局,那么重要)
所以我的查询是:
SELECT user FROM `d_risposte` WHERE user LIKE 'a%' group by user having count(*) > 7
表格结果应为:
user
----
a34
a71
然后我应该计算大部分回复: 但我不知道如何做一个查询, 我试着这样的......
SELECT reply, COUNT(reply) AS fooCount FROM d_risposte WHERE user ????????? GROUP BY reply ORDER BY COUNT(reply) DESC LIMIT 1
我无法弄明白:(
答案 0 :(得分:1)
这是一个有趣的问题,试试这个:
SELECT DISTINCT t.user,
(SELECT s.reply FROM d_risposte s
WHERE s.user = t.user
GROUP BY s.reply
ORDER BY count(*) DESC limit 1) as top_reply
FROM d_risposte t
INNER JOIN(SELECT d.user FROM d_risposte d
WHERE d.user like 'a%'
GROUP BY d.user
HAVING count(*) > 6) t2
ON(t2.user = t.user)
这将基本为每个用户选择top_reply
,然后加入表格以过滤那些记录少于7条并且不以a
开头的人
答案 1 :(得分:0)
您可以使用两个聚合执行此操作:
Select user,
Substring_index(group_concat(reply order by cnt desc), ',', 1) as reply
From (select user, reply, count(*) as can't
From d_riposte
Group by user, reply) ur
Group by user
Having sum(cnt) >= 7