我有个ID字段,里面的ID (varchar 50)为, 1.1, 1.2 ,1.1.1, 1.2.1 这样的类型现在我select他之后, order by id 但是排序是混乱的我想要 1.1.1
       1.1.2
       1.1.3
       1.1.4
         *
         *
       1.1.10
       1.1.11但是出来是  1.1.10
            1.1.11
            1.1.5这种不规律的,请问如何排序

解决方案 »

  1.   


    create table tb(col varchar(10))
    insert tb select '1.1.10' 
    insert tb select '2.1.9' 
    insert tb select '1.1.8' 
    insert tb select '1.1.11' select * from tb
    order by cast(Parsename(col,3) as int), 
             cast(Parsename(col,2) as int), 
             cast(Parsename(col,1) as int)/*
    col        
    ---------- 
    1.1.8
    1.1.10
    1.1.11
    2.1.9(所影响的行数为 4 行)
    */
      

  2.   

    create table tb(id varchar(50))
    insert into tb select '1' union all select '1.1' union all select '1.2' union all select '1.12'
    union all select '1.1.1' union all select '1.1.2' union all select '1.1.10' union all select '7'
    union all select '11.1.1'
    go
    ;with cte as(
    select id,(case len(id)-len(replace(id,'.','')) when 0 then id+'.0.0' when 1 then id+'.0' else id end) as o from tb
    )
    select id from cte order by convert(int,parsename(o,3)),convert(int,parsename(o,2)),convert(int,parsename(o,1))
    /*
    id
    --------------------------------------------------
    1
    1.1
    1.1.1
    1.1.2
    1.1.10
    1.2
    1.12
    7
    11.1.1(9 行受影响)
    */
    go
    drop table tb
      

  3.   


    create table tb(col varchar(10))
    insert tb select '1.1.10' 
    insert tb select '2.1.9' 
    insert tb select '1.1.8' 
    insert tb select '1.1.11' select * from tb
    order by Parsename(col,3)+0,Parsename(col,2)+0,Parsename(col,1)+0 
    /*
    col
    ----------
    1.1.8
    1.1.10
    1.1.11
    2.1.9
    */