有一个这样的表字段 id    a        sj
     1     15    2009-11-01
     3     10    2009-11-01
     22    13    2009-11-03
     4     20    2009-11-01
     44    20    2009-11-02
     5     20    2009-11-03
求sql:得到的是每天a字段最大值和最大值的id、最小值值和最小值的id

解决方案 »

  1.   

    select max(a),min(a),max(id),min(id) from t group by sj;分太多了。
      

  2.   

    好像有点不一样,要用分析函数来做
    select *
    from 
    (
    select t.*,row_number() over(partition by sj order by a desc ) max_rn,row_number() over(partition by sj order by a  ) min_rn from t  
    )
    where max_rn=1 or min_rn=1
      

  3.   

    或者写成这样:select * from t t0
    where not exists (select 1 from t t1 where t1.sj = t0.sj and (t1.a > t0.a or t1.a < t0.a) );
      

  4.   

    select m.id, m.a, n.id, n.a 
    from 
    (select t0.* from t t0
    where not exists (select 1 from t t1 where t1.sj = t0.sj and t1.a > t0.a)) m
    (select t0.* from t t0
    where not exists (select 1 from t t1 where t1.sj = t0.sj and t1.a < t0.a)) n
    where m.sj = n.sj;这是字段写在一起的情况呵呵,提供几种可选做法, 算是补过。
      

  5.   

    我要的结果
      sj         maxid     max   minid    min   avg
    2009-11-01    4         20     1      15    15
    2009-11-01    44        20    44      20    20
      

  6.   

    上面写sj写错了
      sj        maxid    max  minid    min  avg 
    2009-11-01    4        20    1      15    15 
    2009-11-02    44        20    44      20    20
      

  7.   

    #8 m后面掉了,
    还有你要的结果和你的描述不符
    2009-11-01的minid和min应该是3,10
      

  8.   

    select m.sj,m.id,m.a,n.id,n.a,k.a from
    (select * from c t0
    where not exists (select t1.sj from c t1 where t1.sj = t0.sj and t1.a > t0.a)) m,
    (select * from c t0
    where not exists (select t1.sj from c t1 where t1.sj = t0.sj and t1.a < t0.a)) n,
    (select sj,avg(a) a from c group by sj) k
    where m.sj = n.sj
    and m.sj = k.sj;mysql 5测试通过,这是通用sql,也适用于oracle
      

  9.   

    呵呵 那我来替shiyiwan讲讲吧 不对的地方请大家指正啊select m.sj,m.id,m.a,n.id,n.a,k.a from
    (select * from c t0
    where not exists (select t1.sj from c t1 where t1.sj = t0.sj and t1.a > t0.a)) m,
    --这个子查询选出了最大值的记录
    (select * from c t0
    where not exists (select t1.sj from c t1 where t1.sj = t0.sj and t1.a < t0.a)) n,
    --这个子查询选出了最小值的记录
    (select sj,avg(a) a from c group by sj) k
    --这个子查询求出了平均值
    where m.sj = n.sj
    and m.sj = k.sj;
    --两个WHERE条件把三个子查询关联起来