代码之家  ›  专栏  ›  技术社区  ›  b0x0rz

是否有用于显示伪随机数据库记录的SQL Server函数?

  •  4
  • b0x0rz  · 技术社区  · 16 年前

    例如:

    • 随机显示10条记录,但是
    • 比最早的更频繁地显示最新的

    • 假设有100个条目 news

    • 第一个(按日期时间)记录被选中的几率几乎为0%

    mssql中有这样的东西吗?或者c中有什么函数(最佳实践)我可以用来实现这个?

    thnx公司

    编辑:我知道这个标题很恐怖。请编辑,如果你有一个更描述性的。thnx公司

    5 回复  |  直到 16 年前
        1
  •  4
  •   Martin Smith    16 年前

    WITH N AS
    (
    SELECT id,
           headline,
           created_date,
           POWER(ROW_NUMBER() OVER (ORDER BY created_date ASC),2) * /*row number squared*/
              ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS [Weight] /*Random Number*/
      FROM news
      )
      SELECT TOP 10 
           id,
           headline,
           created_date FROM N 
      ORDER BY [Weight] DESC
    
        2
  •  2
  •   Remus Rusanu    16 年前

    Limiting Result Sets by Using TABLESAMPLE

    SELECT FirstName, LastName
    FROM Person.Person 
    TABLESAMPLE (100 ROWS);
    

        3
  •  0
  •   EFraim    16 年前

    例如,您可以使用指数分布选择一个N,然后选择TOP(N)ordered by date,然后选择最后一行。

        4
  •  0
  •   Michael Mior Aouidane Med Amine    16 年前

    不幸的是,我不知道MSSQL,但我可以给出一个高级建议。

    1. 将该值除以每列的最大值,得到一个百分比。
    2. 得到一个随机数,乘以上面的百分比。
    3. 按此值对列进行排序并取顶部 N

    这将使最新的结果更加重要。如果要调整较旧结果与较新结果的相对频率,可以在获取比率之前对值应用指数或对数函数。如果你有兴趣,让我知道,我可以提供更多的信息。

        5
  •  0
  •   Mau    16 年前

    如果您可以在DB访问后筛选结果,或者您可以使用 order by 并用阅读器处理结果,然后你可以给选择添加一个概率偏差。你看,偏差越大,测试就越困难 if ,过程越随机。

    var table = ...  // This is ordered with latest records first
    int nItems = 10;  // Number of items you want
    double bias = 0.5;  // The probabilistic bias: 0=deterministic (top nItems), 1=totally random
    Random rand = new Random();
    
    var results = new List<DataRow>();  // For example...
    
    for(int i=0; i<table.Rows.Count && results.Count < nItems; i++) {
        if(rand.NextDouble() > bias)
            // Pick the current item probabilistically
            results.Add(table.Rows[i]);  // Or reader.Next()[...]
    }