日期:2014-05-17  浏览次数:20397 次

把select 随机排序的结果保存在存储过程中的临时表中
本帖最后由 jxst620306 于 2013-08-19 11:01:18 编辑
实例:有一张表如下
 
通过查询语句,最后我要得到的是

得到的结果里面有两列。
就是对于name列有重复行的随机取其中的一行
比如name='b'的取id=2那一行在结果中,当然取id=5的那一行在结果中也可以。
这个问题想了好久,最后写了一个存储过程

CREATE proc Random
as 

CREATE TABLE #a
(
ID [int] NOT NULL,
Name [varchar](50) NOT NULL,
)
insert into #a select * from table order by newid() asc

select * from #a t where 
exists
(
select 1  from 
(
select top 1 * from #a where Name =t.Name 
) as t2 where ID=t.ID
)
drop table #a
GO

insert into #a select * from table order by newid() asc 
这句是把select随机排序的结果插入到临时表

select * from #a t where 
exists
(
select 1  from 
(
select top 1 * from #a where Name =t.Name 
) as t2 where ID=t.ID
)
这个就是查找了。

问题是临时表#a的顺序永远都是不变的。
也就是说查出来的结果永远是
ID Name
1  a
2  b
3  c
ID永远是1,2,3

而我实际写的代码是 
CREATE proc [dbo].[Random]
@CN varchar(50),
@QT varchar(50)
as 

CREATE TABLE #a
(
[ID] [int] NOT NULL,
[CourseName] [varchar](50) NOT NULL,
[KeyPointID] [varchar](50) NOT NULL,
[QusetionType] [varchar](50) NOT NULL,
[Content] [varchar](1000) NOT NULL,
[OptionA] [varchar](100) NOT NULL,
[OptionB] [varchar](100) NOT NULL,
[OptionC] [varchar](100) NOT NULL,
[OptionD] [varchar](100) NOT NULL,
[OptionE] [varchar](100) NOT NULL,
[OptionF] [varchar](100) NOT NULL,
)
insert into #a select * from [dbo].[TB_KeyPoint] where [CourseName]=@CN and [QusetionType]=@QT order by newid() asc

select * from #a t where 
exists
(
select 1  from 
(
select top 1 * from #a where [KeyPointID]=t.KeyPointID