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

请问这个排序怎么做?
我有两列数据
SQL code

ID                name
---------------------------------
1        0301
3        0202
4        0306
5        0904
6        0905
7        0402
8        1101



由于0301比较特殊 
现在我想要的结果是 除了0301要按name来排 其他的都按照ID来排

结果为
SQL code

ID                name
---------------------------------
3        0202
1        0301
4        0306
5        0904
6        0905
7        0402
8        1101


谢谢先

------解决方案--------------------
怎么确定的0301所在行在0202之后。
------解决方案--------------------
SQL code

order by (case when [name] = '0301' then [name] else ltrim(id) end)

------解决方案--------------------
SQL code
create table tb(ID int,name varchar(10))
insert into tb select 1,'0301'
insert into tb select 3,'0202'
insert into tb select 4,'0306'
insert into tb select 5,'0904'
insert into tb select 6,'0905'
insert into tb select 7,'0402'
insert into tb select 8,'1101'
go
select * from tb order by (case when id=3 then -id else id end)
/*
ID          name
----------- ----------
3           0202
1           0301
4           0306
5           0904
6           0905
7           0402
8           1101

(7 行受影响)

*/
go
drop table tb

------解决方案--------------------
order by case when name='0301' then 1 else 0 end ,id
------解决方案--------------------
很简单,把name转为数字型,排序就OK了

select id,name from tb order by convert(int,name)
------解决方案--------------------
哦,不好意思,还有0402在,没看清,见笑了
------解决方案--------------------
如果数据多了,是不是0301这行一直就排第二,不会有其它可能?
------解决方案--------------------
SQL code
create table tb(ID int,name varchar(10))
insert into tb select 1,'0301'
insert into tb select 3,'0202'
insert into tb select 4,'0306'
insert into tb select 5,'0904'
insert into tb select 6,'0905'
insert into tb select 7,'0402'
insert into tb select 8,'1101'
GO
SELECT * FROM TB ORDER BY  CASE WHEN NAME='0301' THEN 0 ELSE 1 END ASC,NAME asc

------解决方案--------------------
不是已经搞定了吗,要么就是你需求不明确