【问题标题】:select random users sql选择随机用户 sql
【发布时间】:2014-06-27 17:51:44
【问题描述】:

在我的一个表格中,我按用户 ID、日期、产品、渠道等列出了购买清单。我想随机选择一组用户,以便进行样本分析。如果我使用 rand(),我将有机会排除用户的第 2 次、第 3 次、第 n 次购买。抓取 50、100、60000 个随机用户并查看他们所有购买的最佳方式是什么?

select userID,
date,
SKU,
Campaign,
Device

where date between '2014-05-01' and '2014-05-31'

from Sales

【问题讨论】:

    标签: sql select random


    【解决方案1】:

    这将选择前 (X) 个用户,以及他们的所有销售数据。

    declare @samplerate int
    set @samplerate = 50
    
    select s.userID,
    s.date,
    s.SKU,
    s.Campaign,
    s.Device
    from Sales s 
    JOIN (select top(@samplerate) RAND() as rnd, x.userID
          from (select distinct userID 
                from Sales) x
          order by rnd) y
       on s.userID = y.userID
    where s.date between '2014-05-01' and '2014-05-31'
    

    【讨论】:

      【解决方案2】:
      DECLARE @UserCount int
      SET @UserCount = 50 --Set number of users
      
      ;WITH 
      UserList AS --Get list of all unique users
      (   SELECT DISTINCT UserID
          FROM Sales
      ),
      RndList AS --Get list of # random users
      (   SELECT TOP(@UserCount) UserID
          FROM UserList
          ORDER BY NewID()
      )
      --Get all Sales records for list of users
      SELECT s.UserID,s.Date,s.SKU,s.Campaign,s.Device
      FROM Sales s
      JOIN RndList r ON r.userID = s.UserID
      WHERE [Date] BETWEEN '2014-05-01' AND '2014-05-31'
      

      【讨论】:

      • 太棒了,谢谢。我是 SQL 新手,所以不知道这是解决方法。我与我公司的一位 DBA 进行了交谈,我们制作了这个解决方案的一个版本。
      猜你喜欢
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 2018-12-04
      • 2012-04-15
      相关资源
      最近更新 更多