如何获取列上每个值集的序列号

时间:2013-12-24 07:17:02

标签: sql performance oracle plsql

Account Number  Balance SequenceNo
12345           100,00  1
12345           120,52  2
12345           90,02   3
54646           100,56  1
51224           98      1
51224           52      2
我有一张桌子,有两列;帐号和余额。如何在帐号上生成SequenceNo?每个帐户都有序列号。请帮忙

3 个答案:

答案 0 :(得分:4)

您只需使用row_number() over()分析函数即可实现此目的:

SQL> with t1(Account_Number, Balance) as(
  2    select 12345, 100.00 from dual union all
  3    select 12345, 120.52 from dual union all
  4    select 12345, 90.02  from dual union all
  5    select 54646, 100.56 from dual union all
  6    select 51224, 98     from dual union all
  7    select 51224, 52     from dual
  8  )
  9  select Account_Number
 10       , balance
 11       , row_number() over(partition by account_number
 12                               order by account_number) as sequence_no
 13    from t1
 14  ;

结果:

ACCOUNT_NUMBER    BALANCE SEQUENCE_NO
-------------- ---------- -----------
         12345        100           1
         12345     120.52           2
         12345      90.02           3
         51224         98           1
         51224         52           2
         54646     100.56           1

6 rows selected

答案 1 :(得分:0)

解决方案是使用row_number()分析函数。

这是SQLFiddle

答案 2 :(得分:0)

假设您的表名是MyTable,以下是您可以实现的目标:

WITH t1 
     AS (SELECT account_number, 
                balance, 
                rownum R_Num 
         FROM   mytable 
         ORDER  BY account_number), 
     t2 
     AS (SELECT account_number, 
                Min(r_num) Min_R_Num 
         FROM   t1 
         GROUP  BY account_number) 
SELECT t1.account_number, 
       t1.balance, 
       t1.r_num - t2.min_r_num + 1 RecordNo 
FROM   t1, 
       t2 
WHERE  t1.account_number = t2.account_number