使用SQL查询在R中循环指数时间

时间:2017-11-15 00:18:15

标签: sql-server r rodbc

我的查询需要花费大量时间才能使用RODBC(+3小时)执行:

    sqlQuery(dbhandle2,
             paste0("
                    USE RCC
                    SELECT
                      B.cCodCta,
                      A.dFecRep,
                      SUM(IIF(A.cCtaCnt LIKE '14_[1-6]%' OR A.cCtaCnt LIKE '81_302%', ISNULL(A.nSaldo, 0), 0)) AS 'nDeuDir' 
                    INTO ##tab_rcc_2
                    FROM DEUDSAL A
                    INNER JOIN ##tab_rcc_1 B
                      ON A.cCodSbs = B.cCodSbs
                    GROUP BY cCodCta,
                             dFecRep"))

但是如果仅对前4000个ID(cCodCta)使用此查询:

    sqlQuery(dbhandle2,
             paste0("
                    USE RCC
                    SELECT
                      B.cCodCta,
                      A.dFecRep,
                      SUM(IIF(A.cCtaCnt LIKE '14_[1-6]%' OR A.cCtaCnt LIKE '81_302%', ISNULL(A.nSaldo, 0), 0)) AS 'nDeuDir' 
                    INTO ##tab_rcc_2
                    FROM DEUDSAL A
                    INNER JOIN ##tab_rcc_1 B
                      ON A.cCodSbs = B.cCodSbs
                    WHERE cCodCta IN ('ID1','ID2',...,'ID4000')
                    GROUP BY cCodCta,
                             dFecRep"))

只需2秒钟。所以我认为创建循环可以解决时间问题:

    tabMesesIncDeudaTot <- NULL
    for(i in 0:((length(cCodCta)%/%4000)-1)){
    temp <-         sqlQuery(dbhandle2,
             paste0("
                    USE RCC
                    SELECT
                      B.cCodCta,
                      A.dFecRep,
                      SUM(IIF(A.cCtaCnt LIKE '14_[1-6]%' OR A.cCtaCnt LIKE '81_302%', ISNULL(A.nSaldo, 0), 0)) AS 'nDeuDir' 
                    FROM DEUDSAL A
                    INNER JOIN ##tab_rcc_1 B
                      ON A.cCodSbs = B.cCodSbs
                    WHERE cCodCta IN ('",paste(cCodCta[(i*4000):(i*4000+4000-1),collapse = "','")],"')
                    GROUP BY cCodCta,
                             dFecRep"))
    tabMesesIncDeudaTot <- rbind(tabMesesIncDeudaTot,temp)
    }

我的错误,因为当 i&gt;时执行时间呈指数增长3 即可。我将不胜感激任何帮助,以了解它为什么会发生以及如何优化执行时间。

0 个答案:

没有答案