有一个表:学生信息
字段名有:ID,班别,姓名,性别……
          1,1,张三,男……
          2,1,张四,男……
          3,1,张五,男……
          ……
我现在要随机得到每个班一位同学的信息如下所示:
          ID,班别,姓名,性别……
          2,  1, 张四,男……
          58, 2, 李三,男……
          145,3,赵二,男……
这个查询语句要怎么写呢?
          

解决方案 »

  1.   

    SELECT * FROM table ORDER BY NEWID()
      

  2.   

    -- 每班都有一个学生的随机
    select * from 学生信息表 a where id in (select top 1 id from 学生信息表 where 班别 = a.班别 order by newid()) order by 班别
      

  3.   

    抱歉,没看清题意,更正一下:
    ----创建测试数据
    declare @t table(ID int,班别 int,姓名 varchar(10),性别 varchar(10))
    insert @t
    select 1,1,'张三','男' union all
    select 2,1,'张四','男' union all
    select 3,1,'张五','男' union all
    select 4,2,'张六','男' union all
    select 5,2,'张七','男' union all
    select 6,2,'张八','男' union all
    select 7,3,'张九','男' union all
    select 8,3,'张十','男' union all
    select 9,3,'赵六','男'----查询(每执行一次则ID的值会不同)
    select * from @t as a where ID = (select top 1 ID from @t where 班别 = a.班别 order by newid())/*结果
    ID          班别        姓名         性别         
    ----------- ----------- ---------- ---------- 
    3           1           张五         男
    5           2           张七         男
    9           3           赵六         男
    */
      

  4.   

    declare @t table(ID int,班别 int,姓名 varchar(10),性别 varchar(10))
    insert @t
    select 1,1,'张三','男' union all
    select 2,1,'张四','男' union all
    select 3,1,'张五','男' union all
    select 4,2,'张六','男' union all
    select 5,2,'张七','男' union all
    select 6,2,'张八','男' union all
    select 7,3,'张九','男' union all
    select 8,3,'张十','男' union all
    select 9,3,'赵六','男'select *,guid=newid() into # from @t
    select ID, 班别, 姓名, 性别 from # as a where ID = (select top 1 ID from # where 班别 = a.班别 order by guid)
    drop table #