繁体   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