读书人

一个排序的有关问题不知道要从何入手

发布时间: 2013-10-11 14:52:39 作者: rapoo

一个排序的问题,不知道要从何入手解决。
一个排序的有关问题,不知道要从何入手解决

select code from tb order by code

上面的sql语句得到的结果是这样的,但是我想要的结果是。
1
1-1
1-2
1-19
1-20
2
3
4
5

结果应该要根据阿拉伯数字来排序,code可能会出现1-1-1第三个级别的情况。
请大家帮帮忙。 sql sql?order?by
[解决办法]
引用:
直接你的语句还是可以的啊
--create table #tb
--(
-- code varchar(20) collate Chinese_PRC_CI_AS
--)

--insert into #tb
--select '1'
--union all
--select '1-1'
--union all
--select '1-2'
--union all
--select '1-3'
--union all
--select '1-20'
--union all
--select '2-1'
--union all
--select '2-10'
--union all
--select '3-1'
--union all
--select '4-1'
--union all
--select '5-1'

select * from #tb
order by code

/*
code
--------------------
1
1-1
1-2
1-20
1-3
2-1
2-10
3-1
4-1
5-1
*/


这个例子不够典型。
这样:
1-1
1-2
1-3
1-11
1-20
才能区分
[解决办法]

--1)建函
CREATE function [dbo].[GetSplitOfIndex]
(
@String nvarchar(max),--要分割的字符串
@split nvarchar(10),--分隔符号
@index int--取第几个元素
)
returns nvarchar(1024)
--returns int
as
begin
declare @location int--标记所在位置
declare @start int--标记查找开始位置
declare @next int--
declare @seed int--标记长度

set @String=ltrim(rtrim(@String))--去掉前后空格
set @start=1
set @next=1
set @seed=len(@split)--标记长度赋值

set @location=charindex(@split,@String)
while @location<>0 and @index>@next--在检索完整个字符串或者检测到所选字符串时结束循环
begin
set @start=@location+@seed
set @location=charindex(@split,@String,@start)
set @next=@next+1
END
return
CASE
WHEN CHARINDEX(@split,@String)>0 AND @location =0 THEN ''
WHEN CHARINDEX(@split,@String)=0 AND @location =0 THEN @String
ELSE substring(@String,@start,@location-@start)
end
end
go

--2)行查
;WITH a1 (cstr) AS
(
select '1' UNION ALL
select '1-1' UNION ALL
select '1-1-1' UNION ALL
select '1-2' UNION ALL
select '1-3' UNION ALL
select '1-11' UNION ALL
select '1-20' UNION ALL
select '2' UNION ALL
select '2-1' UNION ALL
select '2-1-1' UNION ALL
select '2-2' UNION ALL
select '2-3' UNION ALL
select '2-20'
)
SELECT * FROM a1
order by
cast(dbo.GetSplitOfIndex(cstr+'-','-',1) AS int)
,cast(dbo.GetSplitOfIndex(cstr+'-','-',2) AS int)
,cast(dbo.GetSplitOfIndex(cstr+'-','-',3) AS int)

[解决办法]
要么像楼上这样 用函数取得每一段转为数值最后合并成一个xxxyyyzzz的前导0的字符串 再按此排序
要么预先为每个建立一个序号字段,按此排序

读书人网 >SQL Server

热点推荐