1. 程式人生 > >SQL SERVER 一組數據按規律橫著放置,少則補空,如人員按一進一出的規律,進出為一組,缺少的補null

SQL SERVER 一組數據按規律橫著放置,少則補空,如人員按一進一出的規律,進出為一組,缺少的補null

排序 loss plink win int div from 規律 sele

假設一組數據:人員進出刷卡數據表【SwingCard】想要變成如下:一進一出為一組橫著排放,缺少數據的補null

ID MenID Door
1 1 In
2 1 In
3 1 Out
4 1 In
5 1 Out
6 1 Out

MenID Door1 Door2
1 In null
1 In Out
1 In Out
1 null Out

實現:

--重新排序,序號為浮點型,裝入臨時表#Copy
select MenID,Door,Row=(Row_Number() over
(order by ID)+0.0) into #Copy from SwingCard --插入一行空數據到臨時表#Copy頭部 insert into #Copy(MenID,Door,Row) values1null , 0.0--相鄰之間錯位連接 with tempLink as (select a.MenID,a.Door Door1,b.Door Door2,a.Row from #Copy a left join #Copy b on a.Row=b.Row-1), --將相鄰之間Door相同的查出來(Door相同,表示該處缺少數據) tempLoss as (select MenId,Null
Door,Row+0.5 Row from tempLink where Door1=Door2) --將缺少的數據補到#Copy insert into #Copy(MenID,Door,Row) select * from tempLoss; --對插入數據的臨時表#Copy重新排序(此時臨時表已經補全數據) with tempNew as (select top 100000 MenID,Door,Row=Row_Number() Over(order by Row) from #Copy), --相鄰之間再次錯位連接 with tempNewLink as (select a.MenID,a.Door Door1,b.Door Door2 from
tempNew a left join tempNew b on a.Row=b.Row-1) --獲取正確數據 select * from tempNewLink where Door1=In or Door2=Out --刪除臨時表 drop table #Copy

SQL SERVER 一組數據按規律橫著放置,少則補空,如人員按一進一出的規律,進出為一組,缺少的補null