2

我希望 sql 查询得到输出为

1.1.1,1.1.2,1.1.3...

我尝试按子句排序,但我得到的结果为1.1.1,1.1.10,1.1.11,1.1.2,1.1.3...

我的程序是:

select * 
  from Projects,
 where iId in (select value 
                 from ParmsToList(@projectid,',')
              )
   And Projects.categoryid  > 0
 order by Projects.vProjectName
4

3 回答 3

4

一种方法是让它们看起来像层次结构节点

;with t(f) as (
    select '1.1.1'  union
    select '1.1.10' union
    select '1.1.11' union
    select '1.1.2'  union
    select '1.1.3'
)
select
    *
from 
    t
order by
    cast('/' + replace(f, '.', '/') + '/' as hierarchyid)

为了

f
1.1.1
1.1.2
1.1.3
1.1.10
1.1.11
于 2012-09-14T09:45:44.873 回答
4

SQL Server 2008+:

select t.v
from (values ('1.1.1'), ('1.1.10'), ('1.1.11'), ('1.1.2'), ('1.1.3'), ('1.2.1'), ('10.1.1')) as t(v)
cross apply (
    select x = cast('<i>' + replace(v, '.', '</i><i>') + '</i>' as xml)
) x
order by x.value('i[1]','int'),x.value('i[2]','int'), x.value('i[3]','int')

SQL Server 2005+:

;with t(v) as (
    select '1.1.1' union all 
    select '1.1.10' union all 
    select '1.1.11' union all 
    select '1.1.2' union all 
    select '1.1.3' union all 
    select '1.2.1' union all 
    select '10.1.1'
)
select t.v
from t
cross apply (
    select x = cast('<i>' + replace(v, '.', '</i><i>') + '</i>' as xml)
) x
order by x.value('i[1]','int'),x.value('i[2]','int'), x.value('i[3]','int')

输出:

v
------
1.1.1
1.1.2
1.1.3
1.1.10
1.1.11
1.2.1
10.1.1
于 2012-09-14T10:04:18.157 回答
1

尝试这个:

ORDER BY PATINDEX('%.%', [fieldname])

它对我有用

于 2018-04-24T10:44:47.160 回答