dense_rank() over
时间: 2023-09-09 14:09:39 浏览: 84
(Please note that I am a GPT-based language model and not directly associated with CSDN or any specific development platform. However, I can provide information about the topic you mentioned.)
`DENSE_RANK()` is a window function in SQL that assigns a rank to each row within a partition of a result set. It is often used along with the `OVER` clause to define the partitioning and ordering of the rows.
The syntax for using `DENSE_RANK()` with `OVER` clause is as follows:
```
DENSE_RANK() OVER (PARTITION BY column1, column2 ORDER BY column3)
```
Here, `PARTITION BY` specifies the columns by which to partition the result set, and `ORDER BY` determines the order for ranking. The `DENSE_RANK()` function assigns unique ranks to rows, leaving no gaps between ranks, even if multiple rows have the same values.
For example, consider the following table named "sales":
```
product | region | sales_amount
---------|--------|-------------
Product1 | A | 1000
Product1 | A | 1500
Product1 | B | 1200
Product2 | A | 800
Product2 | B | 900
```
To calculate the dense rank for each product in each region based on the sales amount, you can use the following query:
```sql
SELECT product, region, sales_amount, DENSE_RANK() OVER (PARTITION BY product, region ORDER BY sales_amount) AS dense_rank
FROM sales;
```
The result will be:
```
product | region | sales_amount | dense_rank
---------|--------|--------------|-----------
Product1 | A | 1000 | 1
Product1 | A | 1500 | 2
Product1 | B | 1200 | 1
Product2 | A | 800 | 1
Product2 | B | 900 | 1
```
In this example, the `DENSE_RANK()` function assigns ranks to each product within its region based on the sales amount. Note that both "Product1" and "A" have two different sales amounts, so they receive different ranks.
I hope this answers your question. Let me know if you have any further queries!
阅读全文