举个例子
表:
productid    color    size    productname
----------------------------------------------
100001        B        L       黑色大号鞋
100001        W        S       白色小号鞋
100002        W        L       白色大号袜子
...          ...      ...      ...
----------------------------------------------这样的数据,我想检索出商品的数据,但同一个商品只要一条记录如:
productid    color    size    productname
----------------------------------------------
100001        B        L       黑色大号鞋
100002        W        L       白色大号袜子如何写sql语句才能做到?主要是如何做到相同的productid只取一条记录?

解决方案 »

  1.   

    select 
        t.* 
    from 
        表 t 
    where 
        not exists(select 
                       * 
                   from 
                       表 
                   where 
                       productid=t.productid 
                       and 
                       productname>t.productname)
      

  2.   

    给你比较全的.          c1   c2    type
     第1行    a     9    5
     第2行    b     8    5
     第3行    c     7    6
     第4行    d     6    6
     第5行    e     5    7
    --@Test
    declare @test table(c1 varchar(1),c2 int,type int)
    insert @test
    select 'a',9,5 union all
    select 'b',8,5 union all
    select 'c',7,6 union all
    select 'd',6,6 union all
    select 'e',5,7--按记录顺序取第一条
    select * from @test a where c1=(select top 1 c1 from @Test where type=a.type)--取最小
    select * from @test a where c1=(select min(c1) from @Test where type=a.type)--取最大
    select * from @test a where c1=(select max(c1) from @Test where type=a.type)--随机取
    select * from @test a where c1=(select top 1 c1 from @Test where type=a.type order by newid())
      

  3.   

    呵呵,楼上忘了把Oracle不支持的 TOP 1 语法改成 rownum 的方式。
      

  4.   


    --按记录顺序取第一条 
    select * from @test a where c1=(select c1 from @Test where type=a.type and rownum = 1) 
      

  5.   

    非常感谢dawugui 
    那么
    --随机取 
    select * from @test a where c1=(select top 1 c1 from @Test where type=a.type order by newid()) 
    改成rownum 的方式,怎么加order by 啊,呵呵,小弟在这方面学识浅薄阿,还请指点
      

  6.   

    select * from table1 a where a.rowid in (select max(b.rowid) from table1 b where a.productid = b.productid) ;
      

  7.   

    give a proposal主要是如何做到相同的productid只取一条记录?
    很复杂〉?select distinct id,color,size
    from t;