表数据如下:
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如何写。

解决方案 »

  1.   


    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
      

  2.   

    order by EDate,CID其实你的要求不是很明确.
    比如 2010-10-24,他们的CID也是一样的,根据你想要的结果看,你还想按照ID排序
      

  3.   

    楼主的结果只有排序,没有分组啊select * from tb order by EDate
      

  4.   

    SELECT * FROM TB AS a ORDER BY (SELECT MIN(EDate) FROM TB WHERE CID=a.CID) ASC,ID ASC
      

  5.   

    --> 测试数据:[tb]
    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*/
      

  6.   

    create table tb(ID int,CID int,EDate datetime)
    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 行)
    */
      

  7.   

    select
     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