表t1,字段f1是nvarchar类型。
记录值为:
f1的值如下:2007年1月
2006年8月
2006年12月
2006年11月如何使其真正按照月份的顺序排序,希望得到的结果如下:2007年1月
2006年12月
2006年11月
2006年8月sql语句怎么写才能搞定?
记录值为:
f1的值如下:2007年1月
2006年8月
2006年12月
2006年11月如何使其真正按照月份的顺序排序,希望得到的结果如下:2007年1月
2006年12月
2006年11月
2006年8月sql语句怎么写才能搞定?
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
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 年,月
order by replace(replace(f1,'年',case len(f1) when 8 then '' else '0' end),'月','')
一定要先化為日期型select * from tb order by cast(replace(replace(f1,'年','-'),'月','')+'01' as datetime) desc
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')
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 行)
*/
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