读书人

把select 随机排序的结果封存在存储过

发布时间: 2013-08-27 10:20:47 作者: rapoo

把select 随机排序的结果保存在存储过程中的临时表中

通过查询语句,最后我要得到的是
把select 随机排序的结果封存在存储过程中的临时表中
得到的结果里面有两列。
就是对于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


) as t2 where ID=t.ID
)
drop table #a
GO


[解决办法]
if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
go
create table #temp( [id] varchar(100), [name] varchar(100));
insert #temp
select '1','a' union all
select '2','b' union all
select '3','c' union all
select '4','c' union all
select '5','c'

--SQL:
;WITH cte AS
(
select rowid=ROW_NUMBER() OVER(PARTITION BY name ORDER BY NEWID()), * from #temp
)
SELECT id, name FROM cte
WHERE rowid = 1
/*
idname
1a
2b
5c
*/

读书人网 >SQL Server

热点推荐