表t1,字段f1是nvarchar类型。
记录值为:
f1的值如下:2007年1月
2006年8月
2006年12月
2006年11月如何使其真正按照月份的顺序排序,希望得到的结果如下:2007年1月
2006年12月
2006年11月
2006年8月sql语句怎么写才能搞定?

解决方案 »

  1.   

    可以搞定,但最彻底的办法是将字段改成datetime,否则麻烦还会很多。
      

  2.   

    order by cast(left(f1,4) as int)*100 + cast(substring(f1, charindex('年',f1)+1, charindex('月',f1)-charindex('年',f1)-1) as int) desc
      

  3.   

    create table tb(f1 nvarchar(100))
    insert tb
    select '2007年1月'
    union select '2006年8月'
    union select '2006年12月'
    union select '2006年11月'select * from tb order by cast(replace(replace(f1,'年','-'),'月','-01') as datetime) descdrop table tb
      

  4.   

    f1的值如下:2007年1月
    2006年8月
    2006年12月
    2006年11月select cast(left(f1,4) as int) 年 , cast(substring(f1,charindex('年',f1) + 1,charindex('月',f1)-charindex('年',f1)-1) as int) 月 from tb
    order by 年,月
      

  5.   

    -- OR
    order by replace(replace(f1,'年',case len(f1) when 8 then '' else '0' end),'月','')
      

  6.   

    order by replace(replace(f1,'年',case len(f1) when 8 then '' else '0' end),'月','') desc
      

  7.   


    一定要先化為日期型select * from tb order by cast(replace(replace(f1,'年','-'),'月','')+'01' as datetime) desc
      

  8.   

    create table tb (f1 varchar(10))
    insert into tb values('2007年1月')
    insert into tb values('2006年8月')
    insert into tb values('2006年12月')
    insert into tb values('2006年11月')select cast(left(f1,4) as int) 年 , cast(substring(f1,charindex('年',f1) + 1,charindex('月',f1)-charindex('年',f1)-1) as int) 月 from tb
    order by 年,月drop table tb/*
    年           月           
    ----------- ----------- 
    2006        8
    2006        11
    2006        12
    2007        1(所影响的行数为 4 行)
    */
      

  9.   


    order by convert(datetime,replace(replace(f1,'年','-'),'月','-')+'1')
      

  10.   

    create table tb (f1 varchar(10))
    insert into tb values('2007年1月')
    insert into tb values('2006年8月')
    insert into tb values('2006年12月')
    insert into tb values('2006年11月')select cast(left(f1,4) as int) 年 , cast(substring(f1,charindex('年',f1) + 1,charindex('月',f1)-charindex('年',f1)-1) as int) 月 
    from tb
    where charindex('年',f1)  > 0 and charindex('月',f1)  > 0
    order by 年,月drop table tb
    /*
    年           月           
    ----------- ----------- 
    2006        8
    2006        11
    2006        12
    2007        1(所影响的行数为 4 行)
    */
      

  11.   

    DECLARE @a TABLE(f1 CHAR(20))
    INSERT INTO @a SELECT
    '2007年1月'
    UNION ALL SELECT '2006年8月'
    UNION ALL SELECT '2006年12月'
    UNION ALL SELECT '2006年11月'
    SELECT * FROM @a order by left(f1,4) desc,CAST(substring(f1,6,len(f1)-6)AS INT) desc
      

  12.   

    还是leo_lesley(leo) 的最可行