【问题标题】:Generating Multiple tables via for loop or apply function in sql query通过for循环或在sql查询中应用函数生成多个表
【发布时间】:2017-07-27 06:50:10
【问题描述】:

我基本上是在运行一个查询来获取给定条件的特定年份的 ID。 例如

table.2001=dbGetquery(conn,"Select ID from base table where x > 3 and year = 2001")

现在我想在这一年(2001 年到 2015 年)进行迭代,我每年都会得到输出 table.2001、table.2002、table.2003 等等。

【问题讨论】:

  • 你的问题是什么?你想从 SO 那里知道什么?
  • 使用SQL IN 选择年份,然后使用R function split 将数据框拆分为基于“年份”列的数据框列表。或者阅读如何通过string into SQL statement as a variable name
  • 您是真的想为每年创建表还是只是将结果集存储在某个变量中?
  • @zx875 - 感谢您的回复 - 但在这里我可以让一个 ID 说 A 在同一年多次出现。我想要不同的 ID,只要它在那一年满足 X>3 一次。而同样的ID,明年可能会再次出现。因此,如果我与 IN 不同,我想它只会在我的工作表中计算该 ID 一次。我在看数据集。 table.2001 = IDs : a , b ,c ,f , table.2002 = IDs a , e , b table.2003 = b , f , d 等等
  • @Maverick - 感谢您的回复。是的,我想通过一个 for 循环分别为每一年创建结果集,或者使用 dbgetQuery 在 R 中使用 sql 查询应用函数

标签: sql r for-loop apply


【解决方案1】:
for (i in (2001:2003)) {
  assign(paste0("df",i),dbGetquery(conn,paste0("Select ID from base table where x > 3 and year = ",i)))
}

【讨论】:

  • @r.user.05.apr - 超级先生!成功了,这就是我要找的!
猜你喜欢
  • 2021-02-09
  • 2017-07-14
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
相关资源
最近更新 更多