分組後取前N條

2021-09-29 14:56:51 字數 1316 閱讀 1829

這種題目面試中經常出現,記錄一下

首先建表

create table `students` (

`id` int(11) not null auto_increment comment '學號',

`clss_id` varchar(2) default null comment '班級id',

`stu_name` varchar(16) default null comment '學生姓名',

`age` int(11) default null comment '學生年齡',

primary key (`id`)

) engine=innodb auto_increment=12 default charset=utf8

插入資料

insert  into `students`(`id`,`clss_id`,`stu_name`,`age`) values 

(1,'a','李明',90),

(2,'a','王磊',95),

(3,'a','孫科',100),

(4,'a','趙強',80),

(5,'a','王智',90),

(6,'b','李海',95),

(7,'b','王峰',84),

(8,'b','魏坤琳',77),

(9,'b','鮑雲',96),

(10,'b','王昱珩',95),

(11,'c','馬芸',92);

表如下

題目一: 求每個班級年齡(分數)最高的前三名

使用連線查詢,連線條件:在同乙個班級,s1.age

題目二: 將所有人的成績從高到低排序

比100大的是0個,比96大的是1個...,然後按ranking asc排序即可

題目三: 取出所有成績的前三名

這個相對簡單一點,只要思路清晰,用子查詢就能做出來

分組取前n條記錄的實現

在oracle中有一資料表exam result 成績記錄表 表中的一條記錄描述了 某個班某個學生某次考試的成績 create table exam result id number 10 not null,主鍵 classid number 10 not null,班級id,關聯到班級表 user...

Mysql取分組後前N個值

表結構如下 create table test group limit row id varchar 33 id int 11 num bigint 11 log varchar 33 insert into test group limit row id id num log values 1 1...

orcale 查詢分組後的前n條記錄

orcale 查詢分組後的前n條記錄 使用row number over partition by col1,col2 order by col3 desc 示例如下 select from select col1,col2,col4,row number over partition by col...