有这表是这样的:
id   xm       mc       fs      sj
1    小王     语文     98      2013-06-17
2    小王     语文     80      2013-06-12
3    小红     语文     90      2013-06-17
4    小红     语文     95      2013-06-13
5    小李     语文     90      2013-06-17
要求写一要sql语句实现每个学生的语文课的第一次考试的成绩,表里存多次考试成绩。
结果应该是:
id   xm       mc       fs      sj
2    小王     语文     80      2013-06-12
4    小红     语文     95      2013-06-13
5    小李     语文     90      2013-06-17

解决方案 »

  1.   

    先group,在having取时间最小的
      

  2.   


    Create table AB
    (
       id int primary key identity(1,1),
      xm nvarchar(8),
      mc nvarchar(30),
       fs  float,
       sj date 
    )
    insert into AB
    select  '小王',     '语文',    98 ,     '2013-06-17'
    union all
    select  '小王',     '语文',    80 ,     '2013-06-12'
    union all
    select  '小红',     '语文',    90 ,     '2013-06-17'
    union all
    select  '小红',     '语文',    95 ,     '2013-06-13'
    union all
    select  '小李',     '语文',    90 ,     '2013-06-17'
    select t1.* from AB t1,
    (select  t.xm,MIN(t.sj) sj from AB t group by t.xm) t2where t1.xm=t2.xm and t1.sj=t2.sj 
    order by t1.sj
    /*
    id          xm       mc                             fs                     sj
    ----------- -------- ------------------------------ ---------------------- ----------
    2           小王       语文                             80                     2013-06-12
    4           小红       语文                             95                     2013-06-13
    5           小李       语文                             90                     2013-06-17(3 行受影响)
    */
      

  3.   

    select 1 as id,N'小王' as xm,N'语文' as mc,98 as fs,'2013-06-17' as sj into #A
    union
    select 2 as id,N'小王' as xm,N'语文' as mc,80 as fs,'2013-06-12' as sj
    union
    select 3 as id,N'小红' as xm,N'语文' as mc,90 as fs,'2013-06-17' as sj
    union
    select 4 as id,N'小红' as xm,N'语文' as mc,95 as fs,'2013-06-13' as sj
    union
    select 5 as id,N'小李' as xm,N'语文' as mc,90 as fs,'2013-06-17' as sjselect * from (
    select *,(select min(sj) from #A where xm=A.xm and mc=a.mc) as minDate from #A A ) A 
    where sj=minDate