日期:2014-05-18 浏览次数:20587 次
分类排序的问题 例如表1: num finisted finisttime 5 完成 13:10 1 未处理 2 完成 20:09 35 完成 15:12 4 完成 14:11 56 未处理 6 完成 23:58 10 未处理 要达以下面这样的结果: 5 完成 13:10 4 完成 14:11 35 完成 15:12 2 完成 20:09 6 完成 23:58 1 未处理 10 未处理 56 未处理 我想实现在这样的分类排序: 先按finisted排序, 如果是完成的,再按finisttime排序, 如果是未处理的,再按num排序. MS SQL2000中,这样的SQL语句如何写呢?
order by finisted,(case when finisted='完成' then finisttime else num)
------解决方案--------------------
if object_id('tb','U') is not null
drop table tb
go
create table tb
(
num int,
finisted varchar(10),
finisttime varchar(10)
)
go
insert into tb
select 5,'完成','13:10' union all
select 1,'未处理','' union all
select 2,'完成','20:09' union all
select 35,'完成','15:12' union all
select 4,'完成','14:11' union all
select 56,'未处理','' union all
select 6,'完成','23:58' union all
select 10,'未处理',''
go
select * from tb order by case when finisted='完成' then 0 else 1 end,finisttime,num
/*
num finisted finisttime
----------- ---------- ----------
5 完成 13:10
4 完成 14:11
35 完成 15:12
2 完成 20:09
6 完成 23:58
1 未处理
10 未处理
56 未处理
(8 行受影响)
*/
------解决方案--------------------
select * from tab order by finisted, (case when finisted='完成' then finisttime else cast(num as varchar) end)
------解决方案--------------------
use Tempdb
go
--> -->
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([num] int,[finisted] nvarchar(3),[finisttime] Datetime)
Insert #T
select 5,N'完成','13:10' union all
select 1,N'未处理',null union all
select 2,N'完成','20:09' union all
select 35,N'完成','15:12' union all
select 4,N'完成','14:11' union all
select 56,N'未处理',null union all
select 6,N'完成','23:58' union all
select 10,N'未处理',null
Go
Select *
from #T
ORDER BY CASE WHEN [finisted]=N'完成' THEN 1 ELSE 2 END,[finisttime],[num]
/*
num finisted finisttime
5 完成 1900-01-01 13:10:00.000
4 完成 1900-01-01 14:11:00.000
35 完成 1900-01-01 15:12:00.000
2 完成 1900-01-01 20:09:00.000
6 完成 1900-01-01 23:58:00.000
1 未处理 NULL
10 未处理 NULL
56 未处理 NULL
*/