[英]Selecting the top 5 in a column with duplicates
I have written a query that gives me a list of data and I need to select the top 5 pieces of data. 我编写了一个查询,该查询提供了一个数据列表,我需要选择前5个数据。 For example 例如
Num Name
5 a
4 b
4 c
2 d
1 e
1 f
1 g
0 h
However if I simply use LIMIT 5, this leaves out data points with name f and g. 但是,如果我仅使用LIMIT 5,则将省略名称为f和g的数据点。 How would I be able to select from ah. 我怎么能从中选择啊。 This is just an example data piece. 这只是一个示例数据。 My actual data contains a lot more rows so I can simply just exclude the bottom row. 我的实际数据包含更多行,因此我可以仅排除底部行。 EDIT sorry when i said top 5 i meant top 5 Num entries. 编辑抱歉,当我说前5名时,我的意思是前5名。 so 5, 4 ,2 ,1,0 but 1 has duplicates so I wanted to select all of these duplicates 所以5、4、2、1,0但1个重复,所以我想选择所有这些重复
You can calculate via adding a new field with an incremental row number within your SQL logic as following: 您可以通过在SQL逻辑中添加具有递增行号的新字段来进行计算,如下所示:
Feeds Num Name
1 5 a
2 4 b
2 4 c
3 2 d
4 1 e
4 1 f
4 1 g
5 0 h
and then limit the result by the required rank (in your case 5). 然后将结果限制为所需等级(在您的情况下为5)。 Following is the SQL for your reference: 以下是SQL供您参考:
SELECT num, name from (
SELECT @row_number:=CASE WHEN @num=num
THEN @row_number ELSE @row_number+1 END AS feeds,@num:=num AS num, name
FROM table1, (SELECT @row_number:=0,@num:='') AS t
ORDER BY num desc
)t1
WHERE feeds <= 5
I think you need a query like this: 我认为您需要这样的查询:
SELECT *
FROM (
SELECT t1.Num, t1.Name, COUNT(DISTINCT t2.Num) AS seq
FROM yourTable t1
LEFT JOIN
yourTable t2
ON t1.Num <= t2.Num
GROUP BY t1.Num, t1.Name) dt
WHERE (seq <= 5);
Check this query 检查此查询
SELECT
t1.Num,
t1.Name,
FIND_IN_SET(t1.Num, SUBSTRING_INDEX(
GROUP_CONCAT(DISTINCT(t2.Num ) ORDER BY t2.Num DESC), ',', 5)
) AS Ord
FROM yourTable t1
LEFT JOIN yourTable t2 ON(t2.Num IS NOT NULL)
GROUP BY t1.Name
ORDER BY t1.Num ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.