0

我需要从庞大的交易数据库中选择所有购物者的代表性样本,以便这些购物者的所有交易都包含在样本中。

桌子:

UserID  TransId
1          1   
1          2
1          3
2          1
2          2
3          1
4          1
4          2
4          3
4          4

50% 购物者样本:

UserID  TransId
2          1
2          2
4          1
4          2
4          3
4          4

如何在 R 中编写 SQL 查询?该表位于 MS SQL Server 中。

4

1 回答 1

2

从 R 连接到 SQL 数据库有很多不同的方法。我个人最喜欢的是这个RODBC包。

RODBC,您可以使用该sqlQuery()函数将SQL查询传递给各种数据库,前提是它们接受 ODBC 连接。

下面的代码将加载RODBC库,分配一个名为的连接con并使用该连接从名为 的表中选择所有记录MyTable

library(RODBC) ###Load library

con <- odbcConnect("POC") ###Assign database connection

sqlQuery(con, "select * from MyTable")

对于您当前的问题,我将使用tablesampleSQLServer 2005 及更高版本上可用的功能。有很多方法可以做到这一点,但下面通过内部连接将表连接到自身的子查询(即 50% 样本)。

查询看起来像这样:

select distinct
  rnd.UserID, TransID
from MyTable 
  join (select UserID 
        from MyTable
        tablesample (50 percent)) rnd
    on rnd.UserID = MyTable.UserID 
 order by rnd.UserID

您可以通过sqlQuery()以下方式:

sqlQuery(con, 
     "select distinct
        rnd.UserID, TransID
      from MyTable 
        join (select UserID 
            from MyTable
            tablesample (50 percent)) rnd
        on rnd.UserID = MyTable.UserID 
      order by rnd.UserID")

这应该会为您提供 50% 的用户 ID 伪随机样本,MyTable其中TransID包含给定UserID.

于 2013-10-30T23:22:02.950 回答