table表里有字段 a b c d 如下    a      b    c     d
2001-1-1  123  张三   备注
2001-1-1  123  李四   备注
2002-1-1  123  张三   备注
2003-1-1  123  李四   备注我要通过查询 如果c字段相同的话 只取时间最大的 查询结果要如下
    a      b    c     d
2003-1-1  123  李四   备注
2002-1-1  123  张三   备注该如何写。。谢谢

解决方案 »

  1.   


    select t.a,t.b,t.c,t.d
    from t  where exists
    (select * from (select c,max(a) a from t group by c )t2 where t.a=t2.a and t.c=t2.c)
      

  2.   

    select a,b,c,d
    from (select a,b,c,d,
     ROW_NUMBER() OVER (PARTITION BY c ORDER BY a desc) as rn from table)
    where rn=1
      

  3.   

    --------- 建表
    CREATE TABLE TABLE_A
    (A DATE,
    B INTEGER,
    C VARCHAR2(10),
    D VARCHAR2(10)

    --------- 测试数据
    INSERT INTO TABLE_A VALUES(TO_DATE('2001-1-1','YYYY-MM-DD'),'123','张三','备注');
    INSERT INTO TABLE_A VALUES(TO_DATE('2001-1-1','YYYY-MM-DD'),'123','李四','备注');
    INSERT INTO TABLE_A VALUES(TO_DATE('2002-1-1','YYYY-MM-DD'),'123','张三','备注');
    INSERT INTO TABLE_A VALUES(TO_DATE('2003-1-1','YYYY-MM-DD'),'123','李四','备注');
    COMMIT;
     --------- SQL
    SELECT A,
           B,
           C,
           D
      FROM (SELECT TABLE_A.*,
                   ROW_NUMBER() OVER(PARTITION BY C ORDER BY A DESC) AS R
              FROM TABLE_A)
     WHERE R <= 1  ----- 可以用 R<= N来确定取前N条记录
    ----------  结果
    A B C D
    2003-1-1 123 李四 备注
    2002-1-1 123 张三 备注
      

  4.   


    select * from tab a
    where not exists(select 1 from tab b where a.c=b.c and a.a<b.a);
      

  5.   

     SELECT MAX(a), b, c, d FROM table_a
     GROUP BY b,c,d
      

  6.   

    SELECT MAX(a), b, c, d FROM table_a GROUP BY b,c,dc字段中的数据并不一定都重复
      

  7.   

    create table times
    (a date,
     b number,
     c varchar2(20),
     d varchar2(20));
    insert into times values(to_date('2001-1-1','yyyy-mm-dd'),123,'tiantom','desc');
    insert into times values(to_date('2001-1-1','yyyy-mm-dd'),123,'tian','desc');
    insert into times values(to_date('2002-1-1','yyyy-mm-dd'),123,'tiantom','desc');
    insert into times values(to_date('2003-1-1','yyyy-mm-dd'),123,'tian','desc');
    commit;select t.a, t.b, t.c, t.d
      from times t
     where exists (select *
              from (select c, max(a) a from times group by c) t2
             where t.a = t2.a
               and t.c = t2.c)
      

  8.   

    select t1.a,.....,t1.d
      from table t1
           (select distinct max(t.a) over(PARTITION BY c ORDER BY a desc) max_date,t.c
              from table) t2
    where t1.a = t2.max_date
      and t1.c = t2.c
      

  9.   

    select a,b,c,d from (select a,b,c,d,row_number() over(partition by c order by a desc) as dateTime  from table) where dateTime=1;