SQL,如何在追加期间输入增量行号?

时间:2016-08-27 07:29:48

标签: sql teradata

我有表格,其中有数据

date       id   $   row_nmbr
1/1/2016    A   40  1
1/2/2016    A   40  2
1/3/2016    A   40  3
1/1/2016    B   40  1
1/2/2016    B   40  2

当我插入一组新数据时,这工作正常,但是当我为现有组合插入数据时,我将行号更改为1.

新数据

date        id  $   
1/4/2016    A   40  

何时插入它我希望它像

一样插入
date       id   $   row_nmbr
1/1/2016    A   40  1
1/2/2016    A   40  2
1/3/2016    A   40  3
1/4/2016    A   40  4<--- New data
1/1/2016    B   40  1
1/2/2016    B   40  2

有关如何在下次插入期间实现此目的的帮助

2 个答案:

答案 0 :(得分:1)

这将增加现有ID的行号,并从新ID开始:

insert into target_table
select src.date, src.id, src.$, 
   row_number() over (partition by src.id order by src.date)
     -- existing number or zero for new ids
   + coalesce(row_nmbrs.max_row_nmbr, 0)
from source_table as src
left join 
 ( -- current row numbers for each id
   select id, max(row_nmbr) as max_row_nmbr
   from target_table
   group by 1
 ) as row_nmbrs
on src.id = row_nmbrs.id

答案 1 :(得分:0)

insert into Table(date, id, `$`, row_nmbr)
  select '01-04-2016', 'A', 40, coalesce(max(row_nmbr),0)+1
    from Table
   where id='A'