Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write transfer with T-SQL

If I need the data through the t-sql syntax transpose What should I do?

BID
-----------------
ID.B1211
50332
50333
50922
50420
50421
50326
50327

I want transpose to

AID BID
----------
ID.B1211
ID.B1211  50332
ID.B1211  50333
ID.B1211  50922
ID.B1211  50420
ID.B1211  50421
ID.B1211  50326
ID.B1211  50327

The real data is like this.Every BatchID's ID at the first. And I want put the ID to another column.The uid is identity and continuous.

uid BatchID
---------------
32  ID.B121129029-14
33  P3YDCS50332
34  P3YDCS50333
35  P3YDCS50922
36  P3YDCS50420
37  P3YDCS50421
38  P3YDCS50326
39  P3YDCS50327
40  P3YDCS50329
41  P3YDCS50328
42  P3YDCS50423
43  P3YDCS50422
44  P3YDCS50921
45  P3YDCS50334
46  P3YDCS50337
47  ID.B121115009-14
48  P3YDCSO0206
49  P3YDCSO0215
50  P3YDCSO0201
51  P3YDCSO0205
52  P3YDCSO0204
53  P3YDCSO0214
54  P3YDCSO0198
55  P3YDCSO0197
56  P3YDCSO0213
57  P3YDCSO0212
58  P3YDCSO0211
59  P3YDCSO0202
60  P3YDCSO0200
61  P3YDCSO0199
like image 680
Shon.Su Avatar asked Oct 05 '22 15:10

Shon.Su


1 Answers

select t.uid, a.batchid bid1, nullif(t.batchid, a.batchid) bid22
from <table> t
cross apply
(select top 1 batchid from <table> where uid <= t.uid and batchid like 'id%' 
  order by uid desc) a
like image 191
t-clausen.dk Avatar answered Oct 10 '22 01:10

t-clausen.dk