Sql 如何在R中使用并行计算?

Sql 如何在R中使用并行计算?,sql,r,sql-server,parallel-processing,database-management,Sql,R,Sql Server,Parallel Processing,Database Management,在我的程序中,我做了一些SQL计算,而不是Select查询。我需要这段代码从2014年运行到2020年,但执行它需要很多时间。有没有办法缩短执行时间?该数据库包含每个市值和行业的许多股票价格 运行一个查询而不是所有循环: sect<-c("Healthcare","Basic Materials","Utilities","Financial Services","Technology","Consumer" "Defensive","Industrials","Comm

在我的程序中,我做了一些SQL计算,而不是Select查询。我需要这段代码从2014年运行到2020年,但执行它需要很多时间。有没有办法缩短执行时间?该数据库包含每个市值和行业的许多股票价格

运行一个查询而不是所有循环:

    sect<-c("Healthcare","Basic Materials","Utilities","Financial Services","Technology","Consumer" 
    "Defensive","Industrials","Communication Services","Energy","Real Estate","Consumer 
    Cyclical","NULL")

    mcap<-c("3 - Large","2 - Mid","1 - Small")

    df_total = data.frame()
    start <- as.Date("01-01-14",format="%d-%m-%y")
    end   <- as.Date("18-03-20",format="%d-%m-%y")
    theDate <- start

    while (theDate <= end){
      for (value1 in sect){
        for (value2 in mcap){
            date=theDate
            sector<-value1
            marketcap1<-value2
            newquery("Select * from table where date='%s' and sector='%s' and marketcap='%s'",date,sector,marketcap1)
   topdemo <- sqlQuery(dbhandle,newquery)
   df=data.frame(topdemo)
   df_total <- rbind(df_total,df)

     }
    }
   theDate <- theDate + 1 
   }
运行大量的小查询会带来很大的开销,其中一个通常会更好

也就是说,您似乎正在移动大量数据。我想知道是否所有的数据移动都是必要的


奇怪的是,您在数千个日期之间循环,但不包括查询中的日期。

是。避免选择*。只选择你需要的列。我实际上用这些数据做了很多计算。Select命令用于引用。从2014年开始,该计划基本上贯穿了每个日期、市值和行业,并计算了一些东西。如何缩短时间?我已经在where条款中包括了日期。我每天都要计算一些事情。我运行了45分钟的程序。它只执行到2014年4月。@Theguy。运行单个查询以将数据加载到数据帧中。如果需要循环遍历数据,请在R中进行。注意,如果操作可以用SQL表示,那么最好在数据库中进行计算。
select *
from table
where sector in ('Healthcare', 'Basic Materials', 'Utilities',
                 'Financial Services', 'Technology', 'Consumer' 
                 'Defensive', 'Industrials', 'Communication Services', 'Energy', 'Real Estate', 'Consumer Cyclical', 'NULL'
                 ) and
        marketcap in ('3 - Large', '2 - Mid', '1 - Small') and
        date between '2014-01-01 and '2020-03-18';