如何从数据表列中选择几个随机值

时间:2013-12-18 20:32:00

标签: c# asp.net sql-server c#-4.0 random

我有一个带有studentid列的DataTable。它有1000条记录。我需要选择大约30个随机ID并将它们插入到数据库表中。然后,我需要排除这30个ID,选择另外30个随机ID,然后......等等,直到1000条记录。

而且,在每次迭代中,我都会有一定数量的id,所以只能选择那么多的id(300不是常数,可能是30,25,23,24 ......)。

3 个答案:

答案 0 :(得分:2)

这可能会让你开始:

--Create a temporary table
CREATE TABLE #temp (id INTEGER)
go

--Insert 30 randow ids into the #temp table, excluding any ids that were previously picked.    
-- run this line as many times as needed.
INSERT INTO #temp select top 30 id from [student] where [id] not in (select [id] from #temp) order by newid()

答案 1 :(得分:1)

创建一个包含1,000个学生ID和shuffle数组的数组。然后从数组的开头开始然后继续。

如果必须持久化,可以将数组的内容写入临时表并按顺序逐步执行。

或者,你可以这样做:

SELECT id FROM table
ORDER BY RAND()

并将其写入临时表。我不记得SQL语法。 SELECT INTO?这将把所有的id以随机顺序放入一个表中,然后你可以从头开始一次挑出30个。

答案 2 :(得分:0)

这里可以容忍使用某些动态SQL。

IF ( OBJECT_ID( 'tempdb.dbo.#t_Student' ) IS NULL )
BEGIN
    CREATE TABLE #t_Student
    (
        StudentID           INTEGER
    );

    SET NOCOUNT ON;

    DECLARE @i  INTEGER;
        SET @i = 0;
    WHILE ( @i < 1000 )
    BEGIN
        INSERT INTO #t_Student ( StudentID )
        VALUES ( @i );
        SET @i = @i + 1;
    END;

    SET NOCOUNT OFF;
END;

IF ( OBJECT_ID( 'tempdb.dbo.#t_Processed' ) IS NOT NULL )
BEGIN
    DROP TABLE #t_Processed;
END;

DECLARE @Random         INTEGER,
        @LowerBound     INTEGER,
        @UpperBound     INTEGER,
        @SQL            NVARCHAR( MAX );
    SET @LowerBound = 1;
    SET @UpperBound = 30;

CREATE TABLE #t_Processed
(
    StudentID           INTEGER
);

WHILE ( (   SELECT  COUNT( 1 )
            FROM    dbo.#t_Processed ) <
        (   SELECT  COUNT( 1 )
            FROM    dbo.#t_Student ) )
BEGIN
    SET @Random = ROUND( ( ( @UpperBound - @LowerBound ) * RAND() + @LowerBound ), 0 );

    SET @SQL = '
        SELECT  TOP ' + LEFT( @Random, 10 ) + ' StudentID
        FROM    #t_Student
        WHERE   StudentID NOT IN (  SELECT  StudentID
                                    FROM    #t_Processed )                          
        ORDER BY NEWID();';
    INSERT INTO #t_Processed ( StudentID )
    EXECUTE dbo.sp_executesql @statement = @SQL;
END;
GO