2017-10-21 58 views
0
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 

Requirement1:對於具有在列2相同的值的所有列,則column4應當按順序編號的Sybase +如何計算序列的編號爲speicific組

Requirement2:對於具有在列2相同值的所有列,第5列應計算爲第3列的當前值 - 第3列的前一值

感謝您的幫助!

我使用的Adaptive Server Enterprise/15.7/EBF 22234 SMP SP121/P/x86_64的/企業版Linux/ase157sp12x /六十四分之三千六百六十位/ FBO/

+0

到目前爲止您嘗試過哪些查詢?哪些Sybase產品(ASE,SQLAnywhere,IQ,Advantage)和哪個版本? – markp

+0

你想對數據做什麼?更新表格?或者只是運行一個可以對行進行排序的選擇? –

+0

它看起來(對我而言)就像您發佈的數據是期望的結果集;如果是這種情況......原始數據是什麼樣的?我建議你看一下[如何創建一個最小的,完整的和可驗證的例子](https://stackoverflow.com/help/mcve),然後回來並更新你的問題,並提供必要的細節來澄清你是什麼'試圖做 – markp

回答

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) 
+0

真棒@RobV !!!!實際上它可以通過使用seq_no = id - (從#t2中選擇min(id),其中tv2.column2 = tv1.column2)+1進一步縮小。另外,最後一個sql不起作用,而我已經使用了和(t2。 seq_no-t1.seq_no)= 1 ..總的來說你的想法很棒!非常感謝 !!!! – user2186469