如何在DB2中按组自动递增

时间:2015-04-20 03:53:18

标签: sql db2 auto-increment

我有一个包含不同类别的数据集 即。

customer_id category
a blue
b blue
c green
d green
e green
f pink
g pink

我想插入一个DB2表,根据我插入的顺序自动递增每个类别的密钥,即

customer_id category auto_incr
a blue 1
b blue 2
c green 1
d green 2
e green 3
f pink 1
g pink 2

然后明天我有了这个新的数据集:

customer_id category auto_incr
h blue
i blue
j pink

我的最终数据集如下:

customer_id category auto_incr
a blue 1
b blue 2
c green 1
d green 2
e green 3
f pink 1
g pink 2
h blue 3
i blue 4
j pink 3

我需要使用DB2 sql执行此操作,并且将不止一次插入此表

1 个答案:

答案 0 :(得分:-1)

您并不需要将这些值存储在表格中,因为您可以动态地推导出这些值:

SELECT 
 customer_id 
 ,category 
 ,ROW_NUMBER() OVER (PARTITION BY category ORDER BY customer_id) AS auto_incr
FROM
 yourtable
ORDER BY 1
相关问题