如下表:
ID1      ID2
15 17
15 18
16 19我想通过查询获得如下结果:
ID1      ID2
15 17
16 19DISTINCT函数只能包含相同的字段,但我想查询出不相同的ID1和ID2。

解决方案 »

  1.   

    declare @t table(ID1 int,ID2 int)
    insert @t
    select 15, 17 union all
    select 15, 18 union all
    select 16, 19select * from @t as a where not exists(select 1 from @t where ID1 = a.ID1 and ID2 < a.ID2)/*结果:
    ID1         ID2         
    ----------- ----------- 
    15          17
    16          19
    */
      

  2.   

    declare @t table(ID1 int,ID2 int)
    insert @t
    select 15, 17 union all
    select 15, 18 union all
    select 16, 19----方法1:
    select * from @t as a where not exists(select 1 from @t where ID1 = a.ID1 and ID2 < a.ID2)
    ----方法2:
    select * from @t as a where ID2 = (select min(ID2) from @t where ID1 = a.ID1)
    ----方法3:
    select a.* from @t as a 
    INNER JOIN (select ID1, min(ID2) as ID2 from @t group by ID1) as b
    on a.ID1 = b.ID1 and a.ID2 = b.ID2
    /*结果:
    ID1         ID2         
    ----------- ----------- 
    15          17
    16          19
    */
      

  3.   

    新建的SQL群 19078538 欢迎大家加入,共同研究,一起进步!
      

  4.   

    create table test(id1 int,id2 int)
    insert test select 15,17
    union all select 15,18
    union all select 16,19
     
    select id1,min(id2) id2 from test group by id1drop table test/----------------------/结果
    15 17
    16 19
      

  5.   

    binglengdexin2() 的方法省事.hellowork(一两清风) 为什么要考虑子查询之类呢?
      

  6.   

    因为楼主没有具体说明是求ID2的最小值还是求ID2最小值所在的行,所以就假设楼主要求的每个ID1相同的ID2最小的那一行了.虽然本题中求最小值和最小值所在的行的结果相同,但含义却大相径庭,这样写可能相对于楼主的简单需求来说是多虑了.
      

  7.   

    hellowork(一两清风) 的方法最好, binglengdexin2() 的虽然省事,但是在很多情况下不适用
      

  8.   

    hellowork(一两清风)考虑得比较周全
     高手真多啊
      

  9.   

    ----方法1:
    select * from @t as a where not exists(select 1 from @t where ID1 = a.ID1 and ID2 < a.ID2)
    这句里面的子查询select 1 from @t where ID1 = a.ID1 and ID2 < a.ID2中
    为什么写成select 1 而不写成select * 呢?这个有什么区别
      

  10.   

    如果表不止2列的話,binglengdexin2() 的方法就行不通了所以還是hellowork(一两清风) 的方法更通用,呵呵
      

  11.   

    我初学SQL,几个星期而已,我只是看题目就写..
      

  12.   

    多多益善啊,如果对ID2没有要求的话,还是选择使用MIN和MAX函数性能好一些!
      

  13.   


    select * from tbl a
    where not exists(select 1 from tbl where a.id1=id1 and a.id2>id2 )
      

  14.   

    hellowork(一两清风):
    select * from @t as a where not exists(select 1 from @t where ID1 = a.ID1 and ID2 < a.ID2)
    这句话意思看不懂,不知能否给解释一下,谢谢。
      

  15.   

    liangpei2008(笑青天) ( ) 信誉:100    Blog   加为好友  2007-07-10 12:20:30  得分: 0  
     
     
       binglengdexin2
    牛!!:)