现在有一张表RepLogs,如下:
  id     emCode   
-------------------
  1      00891
  2      00567
  3      00140
  4      00891
  5      00214
  6      00140id为自动增长,emCode字符类型
现需要一SQL语句,得到如下表:
id      emCode
--------------------
6       00140
5       00214
4       00891
2       00567 要求:id为降序,emCode做类似group by或distinct方法筛选重复的。
最好用一句SQL语句达到效果,不需要存储过程或其它方法
谢谢!

解决方案 »

  1.   

    select * from tb a
     where not exists(select 1 from tb where emCode=a.emCode and id>a.id)
    order by id desc
      

  2.   

    select max(id) id,emCode from tb group by emCode order by 1
      

  3.   

    select max(id) id,emCode from tb group by emCode order by 1 desc
      

  4.   

    select
       *
    from
      tb t
    where
      id=(select max(id) from tb where emCode=t.emCode)
    order by
      id desc
      

  5.   

    select max(id) id,emCode from tb group by emCode order by id desc
      

  6.   


    create table test2(id int,emcode varchar(50))insert test2 
    select 1,'00891'
    union all
    select 2,'00567'
    union all
    select 3,'00140'
    union all
    select 4,'00891'
    union all
    select 5,'00214'
    union all
    select 6,'00140'
    select max(id) as id ,emcode from test2 group by emcode order by id desc
    前面肿么这么快
      

  7.   


          CREATE TABLE #tb1
          (
    id INT IDENTITY(1,1),
    emCode VARCHAR(50)   
          )
          
          INSERT INTO #tb1 VALUES ('00891')
          INSERT INTO #tb1 VALUES ('00567')
          INSERT INTO #tb1 VALUES ('00140')
          INSERT INTO #tb1 VALUES ('00891')
          INSERT INTO #tb1 VALUES ('00214')
          INSERT INTO #tb1 VALUES ('00140')
          
        
     SELECT T2.* FROM  (SELECT MAX(id) id FROM #tb1 GROUP BY emCode) T1 INNER JOIN #tb1 T2 ON T1.id = T2.id ORDER BY T1.id DESC
     
     DROP TABLE #tb1/*id          emCode
    ----------- --------------------------------------------------
    6           00140
    5           00214
    4           00891
    2           00567(4 行受影响)*/
      

  8.   


    select * from 
    (select * ,row_number() over (partition by emCode order by id desc) as row from RepLogs)
    as T where T.row = 1