如何在SQL中设置一定数量的重复项的范围之间创建随机数

问题描述

我有一个访问数据库,其中包含一个名为“ Lab_Samples”的表,该表具有以下字段

Lab_Sample_ID-唯一值 Batch_No-样本所属的一批工作。 Box_No-样本应进入1到10之间的框号No。

每批次有60个样本,我想将Lab_Sample_ID随机分配给1至10之间的Box_no。每个箱子必须有正好6个样本,所以随机数必须正好重复6次

我将如何在sql / Access中做到这一点?

感谢您的帮助

解决方法

您可以在我的项目VBA.Random中使用函数 QrnInteger

在线注释显示了典型用法:

' Retrieves one random integer value between a minimum and a maximum value.
' By default,a value of 0 or 1 will be returned.
'
' The minimum and maximum values can be preset by calling the functions:
'
'   QrnIntegerMaximum NewMaximumValue
'   QrnIntegerMinimum NewMinimumValue
'
' Acceptable minimum/maximum values are about +/-10E+16.
'
' Example:
'   QrnIntegerMinimum 10
'   QrnIntegerMaximum 20
'   RandomInteger = QrnInteger
'   RandomInteger -> 14
'
' Values will be retrieved from the source in batches to
' relief the burden on the API service and to speed up
' the time to retrieve single values.
'
' The default size of a batch is preset by the constant
' DefaultSize in function QrnIntegerSize.
' The size of the batch (cache) can be preset by calling the function:
'
'   QrnIntegerSize NewCacheSize
'
' Argument Id is for use in a query to force a call of QrnInteger
' for each record to retrieve a random id:
'
'   Select *,QrnInteger([SomeField]) As RandomId
'   From SomeTable
'
' Minimum and/or maximum values of the retrieved ids can be set
' from the query itself,for example 1 and 100 respectively:
'
'   Select *,QrnInteger([SomeField]) As RandomId
'   From SomeTable
'   Where QrnIntegerMinimum(1) > 0 And QrnIntegerMaximum(100) > 0
'
' 2019-12-26. Gustav Brock,Cactus Data ApS,CPH.
'
Public Function QrnInteger( _
    Optional Id As Variant) _
    As Variant

    Static Values           As Variant
    Static LastIndex        As Long
    Static CurrentMaximum   As Variant
    Static CurrentMinimum   As Variant
    
    Dim Value               As Variant
    
    If CurrentMaximum <> QrnIntegerMaximum Or CurrentMinimum <> QrnIntegerMinimum Then
        ' Reset cache.
        CurrentMaximum = QrnIntegerMaximum
        CurrentMinimum = QrnIntegerMinimum
        LastIndex = 0
    End If
    
    If LastIndex = 0 Then
        ' First run,a reset,or all values have been retrieved.
        ' (Re)set LastIndex to the size of the cache.
        LastIndex = QrnIntegerSize
        ' Retrieve a new set of values.
        Values = QrnIntegers(LastIndex,CurrentMinimum,CurrentMaximum)
    End If
    
    ' Get the next value.
    ' The index of the array is zero-based.
    LastIndex = LastIndex - 1
    Value = Values(LastIndex)
    
    QrnInteger = Value

End Function

根据您的情况,您可以设置缓存:

QrnIntegerSize 60