Total Pageviews

2014/11/18

[Oracle] How to add serial number for each record

Requirement
Here is my SQL statement to do query:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
SELECT YYY_MM,
       ASP,
       ITEM_CD,
       ITEM_NM,
       AMT_A,
       AMT_B,
       AMT_C
FROM FMS420FA
WHERE YYY_MM='10210'
ORDER BY ASP

Query result:

If I would like to add serial number for each record as bellowing, how to do it?


Solution
We can make good use of ROW_NUMBER function. ROW_NUMBER is an analytic function. It assigns a unique number to each row to which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the order_by_clause, beginning with 1.


The SQL statement had been revised as following:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
SELECT ROW_NUMBER() OVER (PARTITION BY YYY_MM
                          ORDER BY ASP) SEQ,
                                        YYY_MM,
                                        ASP,
                                        ITEM_CD,
                                        ITEM_NM,
                                        AMT_A,
                                        AMT_B,
                                        AMT_C
FROM FMS420FA
WHERE YYY_MM='10210'



Reference
[1] https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm

No comments: