---
title: "row_number() and partition"
author: "caiwenhn2008"
date: "2016-08-30T17:32:59Z"
tags: []
categories: ["企业架构"]
slug: "row-number-and-partition"
draft: false
lastmod: "2016-08-31T11:39:43Z"
id: 2321716
url: "https://caerun.iteye.com/blog/2321716"
---

> 一个表有三列，id，name，score，现在要取得每个人分数最高的两门课程



```java
create temp table tmp_xxx
as
select 1 id,'A' name,80 grade
UNION ALL
select 2,'A',90
UNION ALL
select 3,'A',60
UNION ALL
select 4,'B',100
UNION ALL
select 5,'B',90
UNION ALL
select 6,'B',50;



select id,name,grade
from 
(
select id,name,grade, row_number() over (partition by name order by grade desc) as RN
from
tmp_xxx
) tmp
where RN<=2;

```