从表中选择随机记录,但不超过2个同名记录

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从表中选择随机记录,但不超过2个同名记录相关的知识,希望对你有一定的参考价值。

我想从表中获取TOP N个随机记录,但相同名称的记录不超过2条。

SELECT TOP 7 Table1.ID, Table1.Name, Table1.Salary, Rnd(Abs([Table1]![id])) AS Expr1
FROM Table1
GROUP BY Table1.ID, Table1.Name, Table1.Salary, Rnd(Abs([Table1]![id]))
ORDER BY Rnd(Abs([Table1]![id]));

它给出了两个以上相同名称的记录。有人可以提供帮助吗?

答案

使用此查询:

SELECT 
    ID, 
    [Name]
FROM 
    [Table1]
ORDER BY 
Rnd(-Timer()*[ID]);

然后将其作为Recordset打开,并从头开始遍历并选择ID(可以保存在数组中),同时记录使用的Name(可以为此使用Collection)。] >

如果两次使用名称,则跳过记录并移至下一个。

选择了七个ID后,请停止。 ID数组将标识您的七个记录。

将查询另存为RandomAll

。然后在此功能中使用它:
Public Function RandomTwo() As long()

    Dim rs      As DAO.Recordset
    Dim Names   As New Collection
    Dim Used    As Integer
    Dim Index   As Integer

    Dim Ids()   As Long

    Set rs = CurrentDb.OpenRecordset("RandomAll")

    ReDim Ids(0)
    Do While Not rs.EOF
        Used = 0

        ' Read used count. Will fail if not used.
        On Error Resume Next
        Used = Val(Names.Item(rs.Fields(1).Value))
        On Error GoTo 0
        Debug.Print Used, ;

        If Used = 1 Then
            ' Remove key to be added later with updated use count.
            Names.Remove rs.Fields(1).Value
        End If
        If Used < 2 Then
            ' Record the use count (as text) of the key.
            Names.Add CStr(Used + 1), rs.Fields(1).Value
            Debug.Print rs!ID.Value, rs.Fields(1).Value
            ' Add ID to array.
            Ids(UBound(Ids)) = rs!ID.Value
            If UBound(Ids) = 6 Then
                ' Seven IDs found.
                Exit Do
            Else
                ' Prepare for next ID.
                ReDim Preserve Ids(UBound(Ids) + 1)
            End If
        End If
        rs.MoveNext
    Loop
    rs.Close

    ' List the found IDs.
    For Index = LBound(Ids) To UBound(Ids)
        Debug.Print Index, Ids(Index)
    Next

    ' Return the IDs.
    RandomTwo = Ids

End Function

该函数将返回包含七个ID的数组。

另一答案

[从古斯塔夫的答案中得到启发,我设计了一些VBA代码,该代码将生成一个SQL字符串,使用该字符串将为您提供N数量的随机记录,每个名称的限制为2。

以上是关于从表中选择随机记录,但不超过2个同名记录的主要内容,如果未能解决你的问题,请参考以下文章

查询效率 - 从表中选择 2 个最新的“组/批次”记录

Sqoop 导入查询以从表中传输 1000 条随机记录?

SQL Server CE性能,从表中选择7000条记录需要8s

用于从表中选择具有最新时间戳的行的 JOOQ 代码

从表中选择最后修改的数据记录

从表中选择记录,其中表名来自另一个表