Skip to content
Advertisement

Dense rank is not generating rows correctly

I have a table A:

I have inserted 11 rows.

+ -----+--------+-----+------------+
| 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:

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:

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