将SQL输入日期范围传递给SHINY中的查询

时间:2016-08-04 14:49:37

标签: sql-server r shiny rodbc shinydashboard

我正在学习使用闪亮和闪亮的仪表板并使用SQL数据库SQL数据库,我希望直接从数据库中提取数据。本质上,我们的想法是合并到表格中的列,这些列具有日期范围的起点和停止点,将它们制成表格然后再绘制它们。

我发现以下帖子介绍了如何将sql输入语句传递给shiny: How to pass input variable to SQL statement in R shiny?

不幸的是,当我尝试应用这个时,我得到一个错误'下标超出范围;它看起来似乎没有被提入。我已经单独测试了它,并且能够提取数据并在没有问题的情况下完成每个步骤。我正在使用RODBC包,我想知道这是不是问题。以下是我的代码:

         library(stringr)
        library(RODBC)
          library(circlize)
         library(shinydashboard)
         library(shiny)

                ui <- dashboardPage(skin = "blue",
                dashboardHeader(title = "sample"),
                dashboardSidebar(disable = TRUE),
                dashboardBody(
                  # Boxes need to be put in a row (or column)
                  fluidRow(
                    box(title = "Route Volume", background = "green", solidHeader = TRUE,
                        plotOutput(outputId= 'plot2'))),
                    fluidRow( 
                      box(background= "green", dateRangeInput("dates", label = h3("Date Range"),start = '2016-06-01',
                                                              end = '2016-06-05')), width = 4

                      ))))

              server <- function(input, output) {
            database = odbcConnect("datatbase")
            output$plot2 = renderPlot({

            d = paste0("SELECT 
               top 30
           convert(char(10),datetime,121) as date, 
           cast(start_destination as varchar(3)) 
           + (',') + cast(final_destination as varchar(3)) as combo,
           count(cast(start_destination as varchar(3)) 
           + (',') + cast(final_destination as varchar(3))) as volume
           FROM
           trips
           WHERE datetime >= ",input$dates[1]," AND
           datetime < ",input$dates[2],"
           GROUP BY
           cast(start_destination as varchar(3)) 
           + (',') + cast(final_destination as varchar(3)),
           convert(char(10),datetime,121);")

        sql = sqlQuery(database, d)

           sql = data.frame(sql, do.call(rbind, str_split(sql$combo, ',')))
       colnames(sql)[colnames(sql)=="X1"] <- "From"
         colnames(sql)[colnames(sql)=="X2"] <- "To"
         sql = sql[,c(4,5,3)]
         sql = sql[order(sql$volume, decreasing = T),]
          chordDiagram(sql)
          circos.clear()

          })

          }


          shinyApp(ui, server)

我确定这是一个愚蠢的错误,缺少引号或我对如何应用这些技术的误解。感谢帮助!!

                ##adding edits by Dean to test



              database = odbcConnect("database")
             output$plot2 = renderPlot({
              if(input$dates[1]!= "") {
               d = paste0("SELECT 
            top 30
          convert(char(10),datetime,121) as date, 
          cast(start_destination as varchar(3)) 
          + (',') + cast(final_destination as varchar(3)) as combo,
          count(cast(start_destination as varchar(3)) 
          + (',') + cast(final_destination as varchar(3))) as volume
          FROM
           trips
           WHERE 
           datetime >= ",input$dates[1]," AND
           datetime < ",input$dates[2],"
           GROUP BY
          cast(start_destination as varchar(3)) 
          + (',') + cast(final_destination as varchar(3)),
           convert(char(10),datetime,121);")
         sql = sqlQuery(database, d) 

        #i assumed the if statement ended here so I put the 
        #bracket below 
           sql = data.frame(sql, do.call(rbind, str_split(sql$combo, ',')))
       colnames(sql)[colnames(sql)=="X1"] <- "From"
         colnames(sql)[colnames(sql)=="X2"] <- "To"
         sql = sql[,c(4,5,3)]
         sql = sql[order(sql$volume, decreasing = T),]
          chordDiagram(sql)
          circos.clear() 

}
    })

   }

按照NJburgo的建议对服务器进行编辑                    ################################## NJburgo建议############## ##                    #I得到错误:不知道如何将输入$ date转换为类日期

                       database = odbcConnect("database")
                           output$plot2 = renderPlot({
                           dates = as.Date(input$dates)
                           d = paste0("SELECT 
                       top 30
                      convert(char(10),datetime,121) as date, 
                     cast(start_destination as varchar(3)) 
                      + (',') + cast(final_destination as varchar(3)) as combo,
                       count(cast(start_destination as varchar(3)) 
                     + (',') + cast(final_destination as varchar(3))) as volume  
                     FROM
                    trips
                      WHERE 
                      datetime >= {d '",input$dates[1],"'} AND
                       datetime < {d '",input$dates[2],"'}
                        GROUP BY
                      cast(start_destination as varchar(3)) 
                       + (',') + cast(final_destination as varchar(3)),
                        convert(char(10),datetime,121);")
                   sql = sqlQuery(database, d) 


                   sql = data.frame(sql, do.call(rbind, str_split(sql$combo, ',')))
                 colnames(sql)[colnames(sql)=="X1"] <- "From"
                 colnames(sql)[colnames(sql)=="X2"] <- "To"
                 sql = sql[,c(4,5,3)]
                 sql = sql[order(sql$volume, decreasing = T),]
               chordDiagram(sql)
                   circos.clear() 

               })

             }

2 个答案:

答案 0 :(得分:0)

##########################想出答案。它需要所有人的两个建议的组合,确保打印日期并进行转换。谢谢大家!下面是工作代码
source

答案 1 :(得分:-1)

我认为这不是R,更可能是SQL,特别是如果你的查询适用于Shiny之外的普通日期(提示:测试一下,报告回来!)。

对于SQL中的日期比较,始终必须将日期转换为:

...WHERE col_name >= {d '2016-08-04'}...

所以你必须用R格式化日期。最简单的方法是使用格式:

format(Sys.Date(), "{d '%Y-%m-%d'}")