问题描述
我想创建一个查询,为特定字段生成一组随机值。例如,让我们说眼睛的颜色。运行时,查询将返回随机的眼睛颜色。
我知道如何使用眼睛颜色值创建表格,以及如何随机化和选择一个值。 (How to get random record from MS Access database)
但是,我还想确定有多大可能将眼睛颜色作为一个值进行拉取。例如,蓝眼睛的可能性为 15/100,而棕色眼睛的可能性为 60/100。
是否可以创建字段和/或查询/sql 公式来实现此目的?我唯一能想到的就是将每个值实际添加 X 次到表中,但这与规范化背道而驰,感觉可能有更优雅的解决方案。
解决方法
你可以像这样创建一个简单的函数:
Public Function RandomEyeColour() As String
Dim EyeColours As Variant
Dim EyeColourRange As Variant
Dim EyeColour As String
Dim EyeColourValue As Single
Dim index As Integer
EyeColours = Array("Brown","Blue","Grey","Hazel","Green","Amber")
' Eye colour distribution:
' 83%,8%,3%,2%,2%.
' Add up the values.
EyeColourRange = Array(0.83,0.91,0.94,0.96,0.98,1)
Randomize
EyeColourValue = Rnd()
For index = LBound(EyeColours) To UBound(EyeColours)
If EyeColourValue < EyeColourRange(index) Then
EyeColour = EyeColours(index)
Exit For
End If
Next
RandomEyeColour = EyeColour
End Function