sql获取每个类别的最多3个分数行

时间:2016-06-28 13:10:51

标签: mysql sql

我有一张数据表如下:

cat score
a   80
c   88
b   36
b   96
d   99
b   76
d   89
a   50
d   69
b   36
d   59
b   96
b   86
c   98
a   50
a   90
c   83
b   66

如何使用SQL获取每只猫的最多3分?

3 个答案:

答案 0 :(得分:2)

您可以使用变量:

SELECT cat, score
FROM (
  SELECT cat, score,
         @seq := IF(@c = cat, @seq + 1,
                    IF(@c := cat, 1, 1)) AS seq
  FROM mytable
  CROSS JOIN (SELECT @c := '', @seq := 0) x
  ORDER BY cat, score DESC ) AS t
WHERE seq <= 3

答案 1 :(得分:1)

您可以使用union

(select cat, score 
from my_table
where cat='a'
order by score desc
limit 3)
union 
(select cat, score 
from my_table
where cat='b'
order by score desc
limit 3)
union 
(select cat, score 
from my_table
where cat='c'
order by score desc
limit 3)
union 
(select cat, score 
from my_table
where cat='d'
order by score desc
limit 3)

答案 2 :(得分:1)

您可以使用相关查询来执行此操作:

SELECT tt.cat,tt.score FROM (
    SELECT t.cat,t.score,
           (SELECT COUNT(*) FROM YourTable s FROM YourTable s
            WHERE s.cat = t.cat and t.score <= s.score) as cnt
    FROM YourTable t) tt
WHERE tt.cnt < 4