读书人

数组排序有关问题

发布时间: 2012-05-01 12:48:58 作者: rapoo

数组排序问题
有表A 表 。其中有 sz 字段 此字段是 varchar 型 。是数组 其中有6位数字。

把 6个 数字任意提取5个 组成数组,其中数字要按从小到大的顺序排列。

请把这些数组 排列出来。

如 A 表中 sz 字段有如下数据;
1 2 3 4 5 6

5 7 9 10 12 23
。。。。。

那么 1 2 3 4 5 6 组成的数组应该是
1 2 3 4 5
1 3 4 5 6
2 3 4 5 6

5 7 9 10 12 23 同理。
sz字段中有很多数据,所以不能手工。



[解决办法]

SQL code
create table tb(id int identity(1,1),sz varchar(20))insert into tbselect '1,2,3,4,5,6'go;with cte as(    select a.id,        convert(int,substring(a.sz,b.number,charindex(',',a.sz+',',b.number+1)-b.number)) sz    from tb a,master..spt_values b    where b.type = 'P' and b.number between 1 and len(a.sz)        and substring(','+a.sz,b.number,1) = ',')select a.id,a.sz,b.sz,c.sz,d.sz,e.szfrom cte a join cte b on a.id = b.id and a.sz < b.sz           join cte c on b.id = c.id and b.sz < c.sz           join cte d on c.id = d.id and c.sz < d.sz           join cte e on d.id = e.id and d.sz < e.szgroup by a.id,a.sz,b.sz,c.sz,d.sz,e.szdrop table tb/****************************id          sz          sz          sz          sz          sz----------- ----------- ----------- ----------- ----------- -----------1           1           2           3           4           61           1           2           4           5           61           1           2           3           4           51           2           3           4           5           61           1           2           3           5           61           1           3           4           5           6(6 行受影响) 

读书人网 >SQL Server

热点推荐