有一张表,三个字段:hdid,vtime,v 
要查出vtime的最大最小值,以及v的最大值和v最大时所对应的vtime值。用一个sql语句怎么写?

解决方案 »

  1.   

    select hdid,(select max(vtime) from tablename where hdid=a.hdid) as maxvtime,vtime as maxV_Time 
    from tablename a
    where v=(select max(v) from tablename where hdid=a.hdid)
    这是最直观的
      

  2.   

    --上面的少了最小值以及v的最大值
    select hdid,(select max(vtime) from tablename where hdid=a.hdid) as maxvtime,(select min(vtime) from tablename where hdid=a.hdid) as minvtime,v as maxV,vtime as maxV_Time 
    from tablename a
    where v=(select max(v) from tablename where hdid=a.hdid)
      

  3.   

    换思路好一些select a.hdid,max(vtime) as maxvtime,min(vtime) as minvtime,max(v) as maxV,max(case when a.v=t.maxV then vtime else null end) as maxV_Time 
    from tablename a,(select hdid,max(v) as maxV from tablename group by hdid) as t
    where a.hdid=t.hdid
      

  4.   

    晕,上面写漏了select a.hdid,max(vtime) as maxvtime,min(vtime) as minvtime,max(v) as maxV,max(case when a.v=t.maxV then vtime else null end) as maxV_Time 
    from tablename a,(select hdid,max(v) as maxV from tablename group by hdid) as t
    where a.hdid=t.hdid
    group by a.hdid