SELECT customer_id, order_id, order_date, order_total, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS row_num FROM orders; ,请举一个详细的例子
时间: 2024-03-12 16:44:23 浏览: 25
好的,以下是一个详细的例子:
假设有一个订单表 orders,包含以下字段:
- customer_id:客户 ID
- order_id:订单 ID
- order_date:订单日期
- order_total:订单总额
现在我们想要查询每个客户最近的订单,以及该订单在客户的订单中排名,可以使用以下 SQL 语句:
```
SELECT
customer_id,
order_id,
order_date,
order_total,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS row_num
FROM
orders;
```
上述 SQL 语句中的 ROW_NUMBER() 函数是窗口函数,用于将查询结果按照指定的排序方式进行排名。PARTITION BY 子句用于指定分区键,即按照哪个字段进行分组,每个分组内的数据将按照 ORDER BY 子句中指定的字段进行排序,并计算排名。
假设 orders 表中有以下数据:
| customer_id | order_id | order_date | order_total |
|-------------|----------|------------|-------------|
| 1 | 1001 | 2021-01-01 | 100 |
| 1 | 1002 | 2021-02-01 | 200 |
| 2 | 2001 | 2021-03-01 | 150 |
| 2 | 2002 | 2021-04-01 | 300 |
| 2 | 2003 | 2021-05-01 | 250 |
| 3 | 3001 | 2021-06-01 | 120 |
执行以上 SQL 语句后,查询结果如下:
| customer_id | order_id | order_date | order_total | row_num |
|-------------|----------|------------|-------------|---------|
| 1 | 1002 | 2021-02-01 | 200 | 1 |
| 1 | 1001 | 2021-01-01 | 100 | 2 |
| 2 | 2003 | 2021-05-01 | 250 | 1 |
| 2 | 2002 | 2021-04-01 | 300 | 2 |
| 2 | 2001 | 2021-03-01 | 150 | 3 |
| 3 | 3001 | 2021-06-01 | 120 | 1 |
可以看到,查询结果按照 customer_id 进行了分组,并按照 order_date 降序排列。对于每个分组内的数据,根据 order_date 的降序排列,计算出了每个订单在该客户的订单中的排名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)