我写了一个查询,它给了我一个数据列表,我需要选择前5个数据。例如
Num Name
5 a
4 b
4 c
2 d
1 e
1 f
1 g
0 h
但是,如果我只使用LIMIT 5,则会遗漏名称为f和g的数据点。我怎么能从a-h中选择。这只是一个示例数据。我的实际数据包含更多行,所以我可以简单地排除底行。 编辑对不起,当我说前5名我意味着前5名参赛作品。所以5,4,2,1,0但1有重复,所以我想选择所有这些重复
答案 0 :(得分:3)
您可以通过在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
然后将结果限制为所需的等级(在您的情况下为5)。以下是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
答案 1 :(得分:2)
我认为您需要这样的查询:
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);
答案 2 :(得分:0)
检查此查询
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