Friday, March 11, 2011

Numbering for duplicate record

DATA:

We have the following data

john | apple
john | melon
john | grape
jane | orange
jane | apple
mike | mango

Requirement:
We need to create a VIEW that has 2 new columns, c and d where c is the sequence number for every changes in column b and d is the sequence number for every changes in column a

a      | b          | c      | d
john | apple   | 001  | 001
john | melon  | 002  | 001
john | grape  | 003  | 001
jane | orange| 001  | 002
jane | apple  | 002   | 002
mike | mango| 001  | 003

Solution:
SELECT   name a,
           fruit b,
           TO_CHAR(ROW_NUMBER() OVER (PARTITION BY name ORDER BY rn), '009') c,
           TO_CHAR(DENSE_RANK() OVER (ORDER BY name), '009') d
    FROM   (  SELECT   ROWNUM rn, name, fruit FROM yourtable)
ORDER BY   rn


No comments :

Post a Comment