C1(字符),C2(时间),排序
如题:表tb,有
列c1(姓名),列c2(时间),原数据如下:
D 2009-11-1 20:20:11
A 2009-12-1 20:20:11
A 2009-12-1 20:21:12
B 2009-12-1 20:23:01
A 2009-12-1 20:23:09
B 2009-12-1 20:25:44
B 2009-12-1 20:26:56
C 2009-12-1 20:29:11
D 2009-12-2 20:33:19
A 2009-12-4 20:33:19
先按最前时间把D排序出来,然后把D的记录紧跟排在一起;再排比D最前时间下一个时间的A,再把A的记录紧跟排在一起;如此类推,排序下去……的结果如下:
D 2009-11-1 20:20:11
D 2009-12-2 20:33:19
A 2009-12-1 20:20:11
A 2009-12-1 20:21:12
A 2009-12-1 20:33:19
A 2009-12-4 20:23:09
B 2009-12-1 20:23:01
B 2009-12-1 20:25:44
B 2009-12-1 20:26:56
C 2009-12-1 20:29:11
解决方法:
SELECT * FROM tb a
ORDER BY (SELECT min(c2) FROM tb WHERE c1=a.c1),c2
ORDER BY (SELECT min(c2) FROM tb WHERE c1=a.c1),c2
测试代码:
代码
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([c1] varchar(1),[c2] datetime)
insert [tb]
select 'D','2009-11-1 20:20:11' union all
select 'A','2009-12-1 20:20:11' union all
select 'A','2009-12-1 20:21:12' union all
select 'B','2009-12-1 20:23:01' union all
select 'A','2009-12-1 20:23:09' union all
select 'B','2009-12-1 20:25:44' union all
select 'B','2009-12-1 20:26:56' union all
select 'C','2009-12-1 20:29:11' union all
select 'D','2009-12-2 20:33:19' union all
select 'A','2009-12-4 20:33:19'
go
create table [tb]([c1] varchar(1),[c2] datetime)
insert [tb]
select 'D','2009-11-1 20:20:11' union all
select 'A','2009-12-1 20:20:11' union all
select 'A','2009-12-1 20:21:12' union all
select 'B','2009-12-1 20:23:01' union all
select 'A','2009-12-1 20:23:09' union all
select 'B','2009-12-1 20:25:44' union all
select 'B','2009-12-1 20:26:56' union all
select 'C','2009-12-1 20:29:11' union all
select 'D','2009-12-2 20:33:19' union all
select 'A','2009-12-4 20:33:19'