简体   繁体   中英

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.

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.

The grade is on a scale of 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?

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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