id 父序號 子序號 內容
11 1 1 測驗1
11 1 2 測驗2
11 1 3 測驗3
11 1 4 測驗4
11 1 5 測驗5
11 1 6 測驗6
11 1 7 測驗7
11 2 1 測驗1
11 2 2 測驗2
11 2 3 測驗3
11 2 4 測驗4
22 1 1 測驗1
33 1 1 測驗1
33 1 2 測驗2
44 1 1 測驗1
44 1 2 測驗2
44 1 3 測驗3
44 1 4 測驗4
實作效果如下:(0單項 1頭 2身 3尾)
以ID和父序號為條件,只有1條記錄 子序號為0 ;
大于一條記錄,則第1條子序號為子序號1;
最后一天子序號 為 3 中間的子序號為 2
id 父序號 子序號 內容
11 1 1 測驗1
11 1 2 測驗2
11 1 2 測驗3
11 1 2 測驗4
11 1 2 測驗5
11 1 2 測驗6
11 1 3 測驗7
11 2 1 測驗1
11 2 2 測驗2
11 2 2 測驗3
11 2 3 測驗4
22 1 0 測驗1
33 1 1 測驗1
33 1 3 測驗2
44 1 1 測驗1
44 1 2 測驗2
44 1 2 測驗3
44 1 3 測驗4
求大神幫寫個函式,謝謝!
uj5u.com熱心網友回復:
;with t1 as (
select *,row_number() over(partition by id,parentid order by getdate()) as rid from tableName
),t2 as (
select id,parentid,max(rid) as mx from t1 group by id,parentid
)
select a.*,c.* from t1 a
left join t2 b on a.id=b.id and a.parentid=b.parentid
cross apply (
select 0 as sub_id where mx=1
union all
select 1 where rid=1 and mx>1
union all
select 3 where rid=mx and mx>1
union all
select 2 where mx>1 and rid<>1 and rid<>mx
) c
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/86312.html
標籤:疑難問題
上一篇:5G建設中CWDM的應用
下一篇:淺談“新基建”與智能網聯汽
