我有如下表:ID    NAME   TYPE1     P1      C
2     P2      C
3     P4      C
4     P5      A
5     P6      B
6     P7      A
7     P8      B怎样用一条SQL查询语句,查出
TYPE='C',TYPE='A',TYPE='B' ID 最大的各一条记录,一共3条记录?如下3     P4      C
6     P7      A
7     P8      B

解决方案 »

  1.   

    create table test(ID int,NAME char(2),TYPE char(1))
    insert test
    select 1,'P1','C' union all
    select 2,'P2','C' union all
    select 3,'P4','C' union all
    select 4,'P5','A' union all
    select 5,'P6','B' union all
    select 6,'P7','A' union all
    select 7,'P8','B'
    select * from testSELECT * FROM test a WHERE not exists 
    (
    SELECT 1 FROM test b WHERE a.id<b.id and a.type=b.type
    )drop table test
      

  2.   

    declare @tab table(id int,name varchar(20),type varchar(20))insert @tab values(1,'P1','C')
    insert @tab values(2,'P2','C')
    insert @tab values(3,'P4','C')
    insert @tab values(4,'P5','A')
    insert @tab values(5,'P6','B')
    insert @tab values(6,'P7','A')
    insert @tab values(7,'P8','B')select * from @tab a where 1>(select count(*) from @tab b where a.id<b.id and a.type=b.type)
      

  3.   

    select * from test a where id=(select max(id) from test where type=a.type)
      

  4.   


    select max(ID) ID,max(NAME) Name,TYPE from TableName
    group by Type
      

  5.   

    select tb.[id],[name],type
    from tb,(select [id]=max(tb.[id]) from tb group by type) tb1
    where tb.[id]=tb1.[id]