Sybase +如何计算特定组的序列号

时间:2017-10-21 04:22:50

标签: sybase

Date      column1 column2 column3 column4 column5
01-Jan-17 A       AB      10      AB_1    10
02-Jan-17 B       AB      20      AB_2    10
03-Jan-17 C       AB      30      AB_3    10
04-Jan-17 D       AB      20      AB_4    -10
05-Jan-17 E       AB      40      AB_5    20
06-Jan-17 X       GH      30      GH_1    30
07-Jan-17 V       GH      40      GH_2    10
08-Jan-17 A       GH      50      GH_3    10

要求1:对于column2中具有相同值的所有列,column4应按顺序编号

要求2:对于column2中具有相同值的所有列,column5应计算为column3的当前值 - column3的先前值

感谢您的帮助!!

我正在使用Adaptive Server Enterprise / 15.7 / EBF 22234 SMP SP121 / P / x86_64 / Enterprise Linux / ase157sp12x / 3660/64位/ FBO /

1 个答案:

答案 0 :(得分:0)

你可以通过以下多步骤处理实现这一点(我没有测试它,但你会得到这个想法)。假设您的表名为't'。

select your_date, column1, column2, column3, id = identity(9) into #t1 from t order by column2, column3  -- this seems to be the ordering you want?

select column2, min(id) as min_id into #t2 from #t1 group by column2

select #t1.* column4 = (#t1.id - #t2.min_id + 1) into #t3 from #t1, #t2 where #t2.column2 = #t1.column2

select ta.*, column5 = case when tb.id is null or tb.column2 <> ta.column2 then ta.column3 else ta.column3 - tb.column3 from #t3 ta, #t1 tb where ta.id *= (tb.id - 1)