某表数据如下:
字段1        字段2
1            A
1            B
1            C
1            D
2            E
2            F
3            G
3            H
3            I
4            J
5            K
5            L现需要从该表中读取以下结果:2           F
3           G
5           L即:任意条件读取字段1的值(不重复),分别随机读取字段2的值,该SQL语句该怎么写?请高手指点。

解决方案 »

  1.   

    declare @t table(id int,name varchar(10))
    insert @t
    select 1,            'A' union all
    select 1,            'B' union all
    select 1,            'C' union all
    select 1,            'D' union all
    select 2,            'E' union all
    select 2,            'F' union all
    select 3,            'G' union all
    select 3,            'H' union all
    select 3,            'I' union all
    select 4,            'J' union all
    select 5,            'K' union all
    select 5,            'L'----查询
    select top 3 
    id ,
    name = (select top 1 name from @t where id = a.id order by newid())
    from (select id from @t group by id) as a order by newid()/*
    结果:
    id          name       
    ----------- ---------- 
    5           L
    2           E
    3           I
    */