如何按指定的順序獲取資料

2021-03-31 08:56:59 字數 2379 閱讀 6568

測試table

create table table1 (id int,name char)

insert into table1

select 1,'q'

union all select 2,'r'

union all select 3,'3'

union all select 4,'5'

要求按指定的id順序(比如2,1,4,3)排列獲取table1的資料

方法1:使用union all,但是有256條資料的限制

select id,name from table1 where id=2

union all

select id,name from table1 where id=1

union all

select id,name from table1 where id=4

union all

select id,name from table1 where id=3

方法2:在order by中使用case when

select id ,name from t where id in (2,1,4,3)

order by (case id

when 2 then 'a'

when 1 then 'b'

when 4 then 'c'

when 3 then 'd' end)

*以上兩種方法適合在資料量非常小的情況下使用

方法3:使用游標和臨時表

先建乙個輔助表,裡面你需要的順序插入,比如2,1,4,3

create table t1(id int)

insert into t1

select 2

union all select 1

union all select 4

union all select 3

declare @id int                              --定義游標

declare c_test cursor for

select id from t1                       

select * into #tmp from table1 where 1=2     --構造臨時表的結構

open c_test

fetch next from c_test

into @id

while @@fetch_status = 0

begin

--按t1中的id順序插資料到臨時表

insert into #tmp select id,name from table1 where id=@id  

fetch next from c_test  into @id

endclose c_test                  

deallocate c_test

*該方法適合需要按照輔助表的順序重排table的順序時使用

(即輔助表已經存在的情況)

方法4:分割字串引數

select * into #tmp from table1 where 1=2 --構造臨時表的結構

declare  @str  varchar(300),@id  varchar(300),@m  int,@n  int 

set  @str='2,1,4,3,'      ---注意後面有個逗號

set  @m=charindex(',',@str) 

set  @n=1 

while  @m>0 

begin 

set  @id=substring(@str,@n,@m-@n) 

--print  @id 

insert into #tmp select id,name from table1 where id=convert(int,@id)

set  @n=@m+1 

set  @m=charindex(',',@str,@n) 

end 

方法5:使用charindex

select * from t1  order by charindex(convert(varchar(2),id),'2,1,4,3')

測試結果

id          name

----------- ----

2           r

1           q

4           5

3           3

(所影響的行數為 4 行)

如何按指定的順序獲取資料

測試table createtabletable1 idint,namechar insertintotable1 select1,q unionallselect2,r unionallselect3,3 unionallselect4,5 要求按指定的id順序 比如2,1,4,3 排列獲取tab...

按指定排列順序獲取資料的sql語句

測試table create table table1 id int,name char insert into table1 select 1,q union all select 2,r union all select 3,3 union all select 4,5 要求按指定的id順序 比...

hive 按指定順序排序 按指定規則給資料排序。

在excel中,不可能將生活中所有規則都寫入到excel的內建資料裡。生活中,往往要根據實際情況指定規則來排列順序。下例裡,要求按 校長 副書記 副校長 政教主任 德育主任 教務主任 班主任進行排序。怎麼辦?首先 單擊職業列的第1個職務資料b2,右鍵選擇排序 自定義排序。其次 在上述開啟的排序對話方...