表 tab
code  name   time
AB    张三   2011-1-30
AB    张三   2011-1-2
AC    李四   2011-1-29
AC    李四   2011-1-3需要的效果是
code  name   time
AB    张三   2011-1-30
AC    李四   2011-1-29求SQL语句   数据库是 Oracle数据库大神解决啊

解决方案 »

  1.   

    时间是最近的值吗
    想了个试一下
    select code,name,max(time) from tab group by code,name
      

  2.   

    找时间最大的记录吗?一楼的就是答案了。
    或者还有其他字段,但是不能group by就用分析函数row_number
    SELECT   code, name, time
      FROM   (SELECT   code,
                       name,
                       time,
                       ROW_NUMBER () OVER (PARTITION BY code ORDER BY time DESC)
                          rn
                FROM   tab)
     WHERE   rn = 1
      

  3.   

    --如果按照code分组则如下:select t.* from tab t where time = (select max(time) from tab where code = t.code)select t.* from tab t where not exists (select 1 from tab where code = t.code and time > t.time)--如果按照name分组则如下:select t.* from tab t where time = (select max(time) from tab where name = t.name)select t.* from tab t where not exists (select 1 from tab where name = t.name and time > t.time)
      

  4.   

    实测数据:CREATE TABLE T83
    (
        CODE VARCHAR2(20),
        NAME VARCHAR2(20),
        TIME DATE
    );INSERT INTO T83 VALUES('AB', '张三', to_date('2011-01-30', 'YYYY-MM-DD'));
    INSERT INTO T83 VALUES('AB', '张三', to_date('2011-01-02', 'YYYY-MM-DD'));
    INSERT INTO T83 VALUES('AC', '李四', to_date('2011-01-29', 'YYYY-MM-DD'));
    INSERT INTO T83 VALUES('AC', '李四', to_date('2011-01-03', 'YYYY-MM-DD'));
    实测结果: