我正在创建一个简单的闪亮应用程序,要求用户选择一年,然后绘制该年度销售总额的直方图。
我希望闪亮从sql查询中获取年份并将其显示在用户选择的下拉菜单中。
到目前为止,我只设法将参数从闪亮传递到SQL:
R sevrer:
server <- shinyServer(function(input, output) {
output$hist <- renderPlot({
table1 <- dbGetQuery(con, statement =
paste("
SELECT sum(sales_amount) as sum, sum(sales_amount) as sum2
from table s
join table2 c on c.key = s.key
join table3 d on d.date = s.date
WHERE year_number = ",input$segment,"
"))
plot(table1$sum, table1$sum2)
})
})
闪亮:
ui <-(fluidPage(
selectInput(inputId = "segment",
label = "segment",
choices = c('2016', '2017', '2018'),
selected = '2018'),
plotOutput("hist")
))
shinyApp(ui = ui, server = server)
我现在想做相反的事情。 我不想对这些年进行硬编码,而是希望从SQL查询中获取它们。
我不知道如何做到这一点。 提前谢谢!
答案 0 :(得分:0)
您需要计算每次销售的年份,然后使用group by子句按年分组结果。然后进入select子句,你可以每年使用sum()。
答案 1 :(得分:0)
您几乎只想将表数据加载到server <- shinyServer(function(input, output) {
output$hist <- renderPlot({
table1 <- dbGetQuery(con, statement =
paste("
SELECT sum(sales_amount) as sum, sum(sales_amount) as sum2
from table s
join table2 c on c.key = s.key
join table3 d on d.date = s.date
WHERE year_number = ",input$segment,"
"))
plot(table1$sum, table1$sum2)
})
})
区域。如下所示,
R服务器:
table2 <- dbGetQuery (con1, "select year_number from yourtable")
ui <-(fluidPage(
selectInput("segment", "segment", sort(unique(table2$year_number)),selected = NULL),
plotOutput("hist")
))
shinyApp(ui = ui, server = server)
ui:
reqAnimFrame(animate)