簡體   English   中英

對天數的 oracle sql 數據集進行自定義排序

[英]custom sort on oracle sql data set for Days

我有以下每個特定 ID 的數據集

No     Id
1      1
2      1
3      1
4      1
1      2
2      2
3      2
4      2

我想對沒有所需排序的列進行排序,例如如果我想從每個 ID 的第二行開始,數據將像這樣顯示

No     Id
2      1
3      1
4      1
1      1
2      2
3      2
4      2
1      2

所以如果想從任何一行開始,它將像上面一樣排序

一種選擇是以這種方式使用SIGN() function

ORDER BY id, SIGN(no - 1) DESC, no

演示

編輯:如果no從變化開始的值,則使用將 ORDER BY 表達式轉換為以下以及替代變量,例如

ORDER BY id, SIGN(no - &start + 1) DESC, no

演示

要從第二行開始,請嘗試 Query#1 和 Query#2 從第三行開始。

 create table mytable(No int, Id int);
 
 insert into mytable values(1,      1);
 insert into mytable values(2,      1);
 insert into mytable values(3,      1);
 insert into mytable values(4,      1);
 insert into mytable values(1,      2);
 insert into mytable values(2,      2);
 insert into mytable values(3,      2);
 insert into mytable values(4,      2);

查詢#1

 with cte as 
 (  
   select no,id,row_number()over(partition by id order by rownum)rn from 
  (
   select no,id from mytable where no=2
   union all
   select no,id from mytable where no<2
  )t 
 )select no,id from cte

Output:

ID
2 1
3 1
4 1
1 1
2 2
3 2
4 2
1 2

查詢#2:

 with cte as 
 (  
   select no,id,row_number()over(partition by id order by rownum)rn from 
  (
   select no,id from mytable where no=3
   union all
   select no,id from mytable where no<3
  )t 
 )select no,id from cte

Output:

ID
3 1
4 1
1 1
2 1
3 2
4 2
1 2
2 2

db<小提琴在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM