Postgresql编号行组

时间:2015-01-22 12:25:42

标签: postgresql enumeration

我有下一个数据表:

  id    date               another_info   
  1     2014-02-01         lala
  1     2014-03-11         ajskj
  1     2014-05-13         kgfd
  2     2014-02-01         SADA
  3     2014-02-01         sfdg
  3     2014-06-12         fdsA
  4     2015-01-03         lilo
  4     2015-01-07         kjlk

我想附加列'sequence_number':

  id    date           sequance_number    another_info
  1     2014-02-01          1              lala
  1     2014-03-11          2              ajskj
  1     2014-05-13          3              kgfd
  2     2014-02-01          1              SADA
  3     2014-02-01          1              sfdg
  3     2014-06-12          2              fdsA
  4     2015-01-03          1              lilo
  4     2015-01-07          2              kjlk

对于每个id,我计算行。表应按id,date

排序

1 个答案:

答案 0 :(得分:3)

使用window function

select id,"date",another_info, row_number() OVER (ORDER BY id,"date") as sequence_number
from data_table

[编辑]没有意识到您需要按ID进行分区。

SELECT id,"date",another_info, 
row_number() OVER (PARTITION BY id ORDER BY "date") as sequence_number
    FROM data_table