如何解决SQL自定义顺序排序
我有此顺序的数据
Id Name
---- ------------
6783 Football
6783 Football
4394 Football
4394 Football
1786 Cricket
1786 Cricket
3265 Tennis
3265 Tennis
2601 Hockey
2601 Hockey
9554 Badminton
9554 Badminton
1947 Basketball
1947 Basketball
如何按此顺序对这些数据进行排序?
Id Name
---- ------------
6783 Football
4394 Football
1786 Cricket
3265 Tennis
2601 Hockey
9554 Badminton
1947 Basketball
6783 Football
4394 Football
1786 Cricket
3265 Tennis
2601 Hockey
9554 Badminton
1947 Basketball
解决方法
这确实是一种丑陋的方式:
Declare @tbl as table(id int,nme varchar(10))
insert into @tbl values(6783,'Football');
insert into @tbl values(6783,'Football');
insert into @tbl values(4394,'Football');
insert into @tbl values(1786,'Cricket');
insert into @tbl values(1786,'Cricket');
insert into @tbl values(3265,'Tennis');
insert into @tbl values(3265,'Tennis');
insert into @tbl values(2601,'Hockey');
insert into @tbl values(2601,'Hockey');
insert into @tbl values(9554,'Badminton');
insert into @tbl values(9554,'Badminton');
insert into @tbl values(1947,'Basketball');
insert into @tbl values(1947,'Basketball');
select *,ROW_NUMBER()OVER(order by (Select 0)) as rnk2
into #tmp
from @tbl
select * from (
select *,ROW_NUMBER()OVER(PARTITION BY id order by (Select 0)) as rnk from #tmp
) X order by rnk,rnk2
,
要做到这一点,需要一个很大的假设,那就是原始序列可以某种方式重现。仅仅通过将这些行无序地输入数据库,我们将无法保证重现结果。
此代码为原始数据分配一个序列。使用o_seq列,ORDER BY产生请求的订单。
drop table if exists dbo.test_table;
go
create table dbo.test_table(
Id int not null,[Name] varchar(100) not null);
insert dbo.test_table(Id,[Name]) values
(6783,'Football'),(6783,(4394,(1786,'Cricket'),(3265,'Tennis'),(2601,'Hockey'),(9554,'Badminton'),(1947,'Basketball'),'Basketball');
drop table if exists dbo.test_table2;
go
create table dbo.test_table2(
Id int not null,[Name] varchar(100) not null,o_seq int);
/* this is not recomended. I had to visually inspect the rows to make sure this worked */
insert dbo.test_table2 select t.*,row_number() over (order by (select null)) from dbo.test_table t
/* produces the correct sort order */
;with nums_cte as (
select *,(o_seq-1)%2 s2
from dbo.test_table2)
select * from nums_cte
order by s2,o_seq;
,
如果我的理解正确,则您希望每个ID散布一行。如果是这样:
order by row_number() over (partition by id order by id),id desc;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。