日期:2014-05-18  浏览次数:20437 次

这个sql排序又该怎样写?
表t1,字段f1是nvarchar类型。
记录值为:
f1的值如下:

2007年1月
2006年8月
2006年12月
2006年11月

如何使其真正按照月份的顺序排序,希望得到的结果如下:

2007年1月
2006年12月
2006年11月
2006年8月

sql语句怎么写才能搞定?




------解决方案--------------------
order by cast(left(f1,4) as int)*100 + cast(substring(f1, charindex( '年 ',f1)+1, charindex( '月 ',f1)-charindex( '年 ',f1)-1) as int) desc
------解决方案--------------------
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) desc

drop table tb

------解决方案--------------------

一定要先化為日期型

select * from tb order by cast(replace(replace(f1, '年 ', '- '), '月 ', ' ')+ '01 ' as datetime) desc
------解决方案--------------------
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 行)
*/
------解决方案--------------------

order by convert(datetime,replace(replace(f1, '年 ', '- '), '月 ', '- ')+ '1 ')
------解决方案--------------------
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