简体   繁体   English

sql获取每个类别的最高3分

[英]sql get the max 3 score rows for each category

I have a table with data as follows: 我有一个数据表,如下所示:

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

How can I use SQL to get the max 3 score rows for each cat? 如何使用SQL获取每只猫的最高3分行?

You can use variables for this: 您可以为此使用变量:

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

You can use 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)

You can do it with a correlated query : 您可以使用相关查询来做到这一点:

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

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

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