我有一张表,通过查询我已经获得了这个结果。我试图得到每个具有最高计数的用户的名字。
select n.user_id,t.name,count(t.name) ct from
temp_user_batches n inner join tags t on n.id=t.note_id
where user_id IN (9122,9125,9126,9127)
group by n.user_id,t.name order by 1,3 desc
这个查询给了我这个表结果
USERID NAME COUNT
9122 AWESOME 4
9122 BritishLanguage 3
9122 Feeling 3
9122 fantastic 2
9122 blessed 1
9125 BritishLanguage 4
9125 London 3
9125 fantastic 3
9125 EnglishUK 3
9125 calmos 2
9125 AWESOME 2
9125 amazing 2
9126 AWESOME 7
9126 Feeling 3
9126 Gary 2
9126 safe 1
9126 blessed 1
9126 EnglishUK 1
9127 Carl 3
9127 karen 3
9127 kelly 2
我想要获得的结果:
USERID NAME COUNT
9122 AWESOME 4
9125 BritishLanguage 4
9126 Awesome 7
9127 Carl 3
答案 0 :(得分:1)
我更改了几个表格和列标识符 - 以帮助理解......
SELECT x.*
FROM
( SELECT n.user_id
, t.name
, COUNT(t.name) ct
FROM notes n
JOIN tags t
ON n.note_id = t.note_id
WHERE user_id IN (9122,9125,9126,9127)
GROUP
BY n.user_id
, t.name
) x
JOIN
( SELECT user_id
, MAX(ct) ct
FROM
( SELECT n.user_id
, t.name
, COUNT(t.name) ct
FROM notes n
JOIN tags t
ON n.note_id = t.note_id
WHERE user_id IN (9122,9125,9126,9127)
GROUP
BY n.user_id
, t.name
) a
GROUP
BY user_id
) y
ON y.user_id = x.user_id
AND y.ct = x.ct;
答案 1 :(得分:0)
试试这个,它会返回一些无用的列。
Bundle