表数据如下:
ID CID EDate ……
1 1 2010-9-1 ……
2 2 2010-8-7 ……
3 3 2010-10-24 ……
4 3 2010-10-24 ……
5 4 2011-12-15 ……
6 1 2011-11-3 ……
我想先按EDate排序,在对CID分组。想得到的结果如下:ID CID EDate ……
2 2 2010-8-7 ……
1 1 2010-9-1 ……
6 1 2011-11-3 ……
3 3 2010-10-24 ……
4 3 2010-10-24 ……
5 4 2011-12-15 ……
请问这个SQL如何写。
ID CID EDate ……
1 1 2010-9-1 ……
2 2 2010-8-7 ……
3 3 2010-10-24 ……
4 3 2010-10-24 ……
5 4 2011-12-15 ……
6 1 2011-11-3 ……
我想先按EDate排序,在对CID分组。想得到的结果如下:ID CID EDate ……
2 2 2010-8-7 ……
1 1 2010-9-1 ……
6 1 2011-11-3 ……
3 3 2010-10-24 ……
4 3 2010-10-24 ……
5 4 2011-12-15 ……
请问这个SQL如何写。
解决方案 »
- 因排序规则原因引起的中文显示乱码的问题
- SQLserver数据库中数据操作
- 如何将ACCESS数据库转换成SQL?
- 跪求数据库高手,用语法语句帮我写个考勤计算规则!谢谢
- phantomMan(去年Delphi,年底.net,今年5月SQL,现在XML,马上Socket............)接分
- 帮我看一下我的SQL测验成绩,全对么?
- 临时表中怎样用索引分页!
- SQl2005 reporting Services 不能使用的问题,求救~~~
- 在哪里设置SQLSERVER的内存使用限制?
- 高分求救,在"insert into tt3 (tID3) SELECT Name from t_item"这条语句中,如果 t_item表中name字段中包含有 ' 怎样处理 ?
- 关于条件位置的问题
- 新人求助,关于好几个表的查询问题
select m.* from tb m,
(select cid , min(edate) ddate from tb group by cid) n
where m.id = n.id
order by n.edate , m.id
比如 2010-10-24,他们的CID也是一样的,根据你想要的结果看,你还想按照ID排序
if object_id('[tb]') is not null drop table [tb]
create table [tb]([ID] int,[CID] int,[EDate] datetime)
insert [tb]
select 1,1,'2010-9-1' union all
select 2,2,'2010-8-7' union all
select 3,3,'2010-10-24' union all
select 4,3,'2010-10-24' union all
select 5,4,'2011-12-15' union all
select 6,1,'2011-11-3'select * from [tb] t order by (select min([EDate]) from [tb] where CID =t.CID)
/*
ID CID EDate
----------- ----------- -----------------------
2 2 2010-08-07 00:00:00.000
1 1 2010-09-01 00:00:00.000
6 1 2011-11-03 00:00:00.000
3 3 2010-10-24 00:00:00.000
4 3 2010-10-24 00:00:00.000
5 4 2011-12-15 00:00:00.000*/
insert into tb values(1 ,1 ,'2010-9-1')
insert into tb values(2 ,2 ,'2010-8-7')
insert into tb values(3 ,3 ,'2010-10-24')
insert into tb values(4 ,3 ,'2010-10-24')
insert into tb values(5 ,4 ,'2011-12-15')
insert into tb values(6 ,1 ,'2011-11-3')
go
select m.* from tb m,
(select cid , min(edate) Edate from tb group by cid) n
where m.CID = n.CID
order by n.edate , m.iddrop table tb
/*ID CID EDate
----------- ----------- ------------------------------------------------------
2 2 2010-08-07 00:00:00.000
1 1 2010-09-01 00:00:00.000
6 1 2011-11-03 00:00:00.000
3 3 2010-10-24 00:00:00.000
4 3 2010-10-24 00:00:00.000
5 4 2011-12-15 00:00:00.000(所影响的行数为 6 行)
*/
a.*
from
tb a,
(select cid , min(edate) Edate from tb group by cid)b
where
a.CID = b.CID
order by
b.edate , a.id