[英]Controlling result of oracle query
I have a schema like this 我有这样的模式
create table sample(id number ,name varchar2(30),mark number);
Now i has to return names of the top three marks. 现在,我必须返回前三个标记的名称。 How can i write sql query for this?
我如何为此编写SQL查询?
If i use max(mark) it will return only maximum and 如果我使用max(mark) ,它将仅返回max和
select name from sample
returns all the names!! 返回所有名称! I tried in many ways but i was unable to control the result to 3 rows.. Please suggest the way to get rid of my problem..
我尝试了很多方法,但是无法将结果控制为3行。.请提出摆脱问题的方法。
How do you want to handle ties? 您想如何处理关系? If Mary gets a mark of 100, Tom gets a mark of 95, and John and Dave both get a mark of 90, what results do you want, for example?
如果Mary得到100分,Tom得到95分,John和Dave都得到90分,例如,您想要什么结果? Do you want both John and Dave to be returned since they both tied for third?
您是否希望John和Dave都因为并列第三而返回? Or do you want to pick one of the two so that the result always has exactly three rows?
还是要选择两个中的一个,以便结果始终精确地包含三行? What happens if Beth also tied for second with a score of 95?
如果贝丝也以95分并列第二,该怎么办? Do you still consider John and Dave tied for third place or do you consider them tied for fourth place?
您是否仍然认为John和Dave并列第三?
You can use analytic functions to get the top N results though which analytic function you pick depends on how you want to resolve ties. 您可以使用分析函数获得前N个结果,尽管您选择哪种分析函数取决于您要如何解决联系。
SELECT id,
name,
mark
FROM (SELECT id,
name,
mark,
rank() over (order by mark desc) rnk
FROM sample)
WHERE rnk <= 3
will return the top three rows using the RANK
analytic function to rank them by MARK
. 将使用
RANK
分析函数返回前三行,以MARK
对其进行排名。 RANK
returns the same rank for people that are tied and uses the standard sports approach to determining your rank so that if two people tie for second, the next competitor is in fourth place, not third. RANK
为平局的人返回相同的排名,并使用标准运动方法确定您的排名,这样,如果两个人并列第二,则下一个竞争对手排在第四位,而不是第三名。 DENSE_RANK
ensures that numeric ranks are not skipped so that if two people tie for second, the next row is third. DENSE_RANK
确保不跳过数字等级,以便如果两个人并列第二,则下一行为第三。 ROW_NUMBER
assigns each row a different rank by arbitrarily breaking ties. ROW_NUMBER
通过任意打破联系为每一行分配不同的等级。
If you really want to use ROWNUM
rather than analytic functions, you can also do 如果您确实想使用
ROWNUM
而不是解析函数,也可以
SELECT id,
name,
mark
FROM (SELECT id,
name,
mark
FROM sample
ORDER BY mark DESC)
WHERE rownum <= 3
You cannot, however, have the ROWNUM
predicate at the same level as the ORDER BY
clause since the predicate is applied before the ordering. 但是,您不能使
ROWNUM
谓词与ORDER BY
子句处于同一级别,因为该谓词是在排序之前应用的。
SELECT t2.name FROM
(
SELECT t.*, t.rownum rn
FROM sample t
ORDER BY mark DESC
) t2
WHERE t2.rn <=3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.