表tb数据如下:
id  a   b
1   A   2
2   B   3
3   A   1
4   A   3
5   B   1
6   C   2
7   C   1
要求返回这样的记录:A字段各不相同,如果有多个记录的A字段相同则取B字段最小的记录。即:
3   A   1
5   B   1
7   C   1    希望能用尽量简洁的SQL语句实现这样的功能。谢谢

解决方案 »

  1.   


    create table tb
    (id int, a char(1), b int)insert into tb
    select 1, 'A', 2 union all
    select 2, 'B', 3 union all
    select 3, 'A', 1 union all
    select 4, 'A', 3 union all
    select 5, 'B', 1 union all
    select 6, 'C', 2 union all
    select 7, 'C', 1
    ;with t as
    (select row_number() over(partition by a order by b) rn,
    id,a,b from tb
    )
    select id,a,b from t where rn=1id          a    b
    ----------- ---- -----------
    3           A    1
    5           B    1
    7           C    1(3 row(s) affected)
      

  2.   


    go
    if object_id('[tbl]') is not null 
    drop table [tbl]
    go
    create table [tbl](
    [id] int,
    [a] varchar(1),
    [b] int
    )
    go
    insert [tbl]
    select 1,'A',2 union all
    select 2,'B',3 union all
    select 3,'A',1 union all
    select 4,'A',3 union all
    select 5,'B',1 union all
    select 6,'C',2 union all
    select 7,'C',1/*
    要求返回这样的记录:A字段各不相同,
    如果有多个记录的A字段相同则取B字段
    最小的记录。即:
    3 A 1
    5 B 1
    7 C 1
    */
    select id,a,b from(
    select ROW_NUMBER()over(partition by a order by b asc) as num,
    *from tbl) t where t.num=1/*
    id a b
    3 A 1
    5 B 1
    7 C 1
    */
      

  3.   

    谢谢楼上两位,思路应该是一样的,刚验证TravyLee的语句可以用。
    基本功有待加强,第一次看到partition和ROW_NUMBER。