关于dense_rank()函数
dense_rank()是一种窗口函数,它用于计算每个行的排序排名,并且如果存在两个或多个具有相同排序顺序的行,则会为它们分配相同的排名,并跳过下一个排名。这意味着如果有两个或多个行具有相同的排序值,则下一个排名将被跳过,以保持密集的排序。
下面是一个使用dense_rank()窗口函数的例子:
假设有以下销售数据表格:
sales_table
---------------------------------------
| id | product | sales | month | year |
---------------------------------------
| 1 | Product1 | 100 | 1 | 2021 |
| 2 | Product2 | 200 | 1 | 2021 |
| 3 | Product3 | 300 | 1 | 2021 |
| 4 | Product1 | 150 | 2 | 2021 |
| 5 | Product2 | 250 | 2 | 2021 |
| 6 | Product3 | 350 | 2 | 2021 |
| 7 | Product1 | 200 | 3 | 2021 |
| 8 | Product2 | 300 | 3 | 2021 |
| 9 | Product3 | 400 | 3 | 2021 |
---------------------------------------
现在,我们想为每个月的每种产品计算销售额排名,以下是使用dense_rank()窗口函数的SQL查询:
SELECT id, product, sales, month, year,
DENSE_RANK() OVER (PARTITION BY month, product ORDER BY sales DESC) AS sales_rank
FROM sales_table;
在这个查询中,我们使用PARTITION BY子句将数据按月份和产品分组,然后使用ORDER BY子句将销售额按降序排序。最后,我们使用dense_rank()函数来为每个分区中的行计算密集排名。
结果如下:
---------------------------------------------------
| id | product | sales | month | year | sales_rank |
---------------------------------------------------
| 1 | Product1 | 100 | 1 | 2021 | 3 |
| 2 | Product2 | 200 | 1 | 2021 | 2 |
| 3 | Product3 | 300 | 1 | 2021 | 1 |
| 4 | Product1 | 150 | 2 | 2021 | 3 |
| 5 | Product2 | 250 | 2 | 2021 | 2 |
| 6 | Product3 | 350 | 2 | 2021 | 1 |
| 7 | Product1 | 200 | 3 | 2021 | 3 |
| 8 | Product2 | 300 | 3 | 2021 | 2 |
| 9 | Product3 | 400 | 3 | 2021 | 1 |
---------------------------------------------------