Skip to content
Advertisement

Dense rank is not generating rows correctly

I have a table A:

Create table A(
    Name varchar(10),
    Number integer,
    Exc integer,
    D1 date
)

I have inserted 11 rows.

Sel * from A;
+ -----+--------+-----+------------+
| NAME | NUMBER | EXC | D1         |
+ -----+--------+-----+------------+
| a    |      1 |   1 | 2020-02-03 |
| a    |      1 |   2 | 2020-02-03 |
| a    |      1 |   3 | 2020-02-03 |
| a    |      1 |   4 | 2020-02-03 |
| a    |      1 |   1 | 2020-02-04 |
| a    |      1 |   2 | 2020-02-04 |
| a    |      1 |   3 | 2020-02-04 |
| a    |      1 |   1 | 2020-02-05 |
| a    |      1 |   2 | 2020-02-05 |
| a    |      1 |   3 | 2020-02-05 |
| a    |      1 |   4 | 2020-02-05 |
+ -----+--------+-----+------------+

Now, when I apply dense rank like below:

sel vt.*,dense_rank() OVER(PARTITION BY Name,Number,EXC ORDER BY D1 ) AS rn
from vt;

Output:

+ -----+--------+-----+------------+----+
| NAME | NUMBER | EXC | D1         | RN |
+ -----+--------+-----+------------+----+
| a    |      1 |   1 | 2020-02-03 |  1 |
| a    |      1 |   2 | 2020-02-03 |  1 |
| a    |      1 |   3 | 2020-02-03 |  1 |
| a    |      1 |   4 | 2020-02-03 |  1 |
| a    |      1 |   1 | 2020-02-04 |  2 |
| a    |      1 |   2 | 2020-02-04 |  2 |
| a    |      1 |   3 | 2020-02-04 |  2 |
| a    |      1 |   1 | 2020-02-05 |  3 |
| a    |      1 |   2 | 2020-02-05 |  3 |
| a    |      1 |   3 | 2020-02-05 |  3 |
| a    |      1 |   4 | 2020-02-05 |  2 |
+ -----+--------+-----+------------+----+

Expected:

+ -----+--------+-----+------------+----+
| NAME | NUMBER | EXC | D1         | RN |
+ -----+--------+-----+------------+----+
| a    |      1 |   1 | 2020-02-03 |  1 |
| a    |      1 |   2 | 2020-02-03 |  1 |
| a    |      1 |   3 | 2020-02-03 |  1 |
| a    |      1 |   4 | 2020-02-03 |  1 |
| a    |      1 |   1 | 2020-02-04 |  2 |
| a    |      1 |   2 | 2020-02-04 |  2 |
| a    |      1 |   3 | 2020-02-04 |  2 |
| a    |      1 |   1 | 2020-02-05 |  3 |
| a    |      1 |   2 | 2020-02-05 |  3 |
| a    |      1 |   3 | 2020-02-05 |  3 |
| a    |      1 |   4 | 2020-02-05 |  3 | <-- Difference here
+ -----+--------+-----+------------+----+

Advertisement

Answer

Removing column EXC from the PARTITION would give you the results that you expect:

DENSE_RANK() OVER(PARTITION BY Name, Number ORDER BY D1)

Demo on DB Fiddle:

name | number | exc | d1         | rn
:--- | -----: | --: | :--------- | :-
a    |      1 |   1 | 2020-02-03 | 1 
a    |      1 |   2 | 2020-02-03 | 1 
a    |      1 |   3 | 2020-02-03 | 1 
a    |      1 |   4 | 2020-02-03 | 1 
a    |      1 |   1 | 2020-02-04 | 2 
a    |      1 |   2 | 2020-02-04 | 2 
a    |      1 |   3 | 2020-02-04 | 2 
a    |      1 |   1 | 2020-02-05 | 3 
a    |      1 |   2 | 2020-02-05 | 3 
a    |      1 |   3 | 2020-02-05 | 3 
a    |      1 |   4 | 2020-02-05 | 3 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement