简体   繁体   English

基本的SQL分组与百分比

[英]basic sql group by with percentage

I have an issue and NO it is not homework, it's just a programmer who has been away from SQL for a long time having to solve a problem. 我有一个问题, ,没有家庭作业,它只是谁已经从SQL离开不得不解决的一个问题很长一段时间的程序员。

I have the following table: 我有下表:

create table students(
    studentid int identity(1,1), 
    [name] varchar(200), 
    [group] varchar(10), 
    grade numeric(9,2) 
)
go

The group is something arbitrary, assume it's the following "Group A", "Group B"... and so on. 该组是任意的,假设它是以下的“ A组”,“ B组” ...等等。

The grade is on a scale of 0 - 100. 等级为0-100。

If there are 5 students in each group with grades randomly assigned, what is the best approach to getting the top 3 students (the top 80%) based on their grade? 如果每组中有5个学生的成绩被随机分配,那么根据他们的成绩来获得前3名学生(前80%)的最佳方法是什么?

To be more concrete if I had the following: 更具体地说,如果我有以下几点:

Ronald, Group A, 84.5
George H, Group A, 82.3
Bill, Group A, 92.0
George W, Group A, 45.5
Barack, Group A, 85.0

I'd get back Ronald, Bill, and Barack . 我会回去罗纳德,比尔和巴拉克 I'd also need to do this over other groups. 我还需要对其他小组这样做。

Take a look at first part of More with SQL Server 2005 : Top n Per Group, Paging, and Common Table Expressions . 看看SQL Server 2005更多内容的第一部分:每个组的前n个,分页和公用表表达式 To get top 3 students in each group you can use: 要获得每个小组的前三名学生,您可以使用:

SELECT  d.studentid,
        d.name,
        d.group,
        d.grade

FROM   (SELECT  s.studentid,
                s.name, 
                s.group, 
                s.grade
                ROW_NUMBER = ROW_NUMBER() OVER (
                    PARTITION BY s.group
                    ORDER BY s.grade DESC)
        FROM    students s
        ) d

WHERE   d.ROW_NUMBER <= 3

使用TOP (n) PERCENT子句:

SELECT TOP (60) PERCENT * FROM students ORDER BY grade DESC

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

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