首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

简单查询语句?该如何解决

2012-01-13 
简单查询语句?有一个表:学生信息字段名有:ID,班别,姓名,性别……1,1,张三,男……2,1,张四,男……3,1,张五,男…………

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



[解决办法]
SELECT * FROM table ORDER BY NEWID()
[解决办法]
-- 每班都有一个学生的随机
select * from 学生信息表 a where id in (select top 1 id from 学生信息表 where 班别 = a.班别 order by newid()) order by 班别
[解决办法]
抱歉,没看清题意,更正一下:
----创建测试数据
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 赵六 男
*/

[解决办法]
昨夜小楼和一两清风的都有问题,多运行几次就知道了,,,
[解决办法]
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 #

热点排行
Bad Request.