因此,当前我正在编写以查询数据库开始的函数,当前我必须手动更改所拥有的SQL查询。看起来像:
sqlQuery(db_query, 'SELECT * From my_db Where db_date = '2019/12/17' AND (ItemType = 1 or ItemType=2)')
我的第一个问题是如何将日期作为手动输入作为函数的一部分。
我的第二个问题与ItemType有关。大约有700种不同的选择,而我需要尽可能多地接受它们。它们并不总是按顺序排列,甚至不是连续的数字。以下是一些可能最终看起来像的例子:
SELECT * From my_db Where db_date = '2019/12/17' AND (ItemType = 1 or ItemType=2)
或
SELECT * From my_db Where db_date = '2019/12/17' AND (ItemType = 50)
或
SELECT * From my_db Where db_date = '2019/12/17' AND (ItemType = 50 or ItemType=142 or ItemType=65 or ItemType=66)
```)
答案 0 :(得分:1)
使用sprintf
可以很好地控制字符串格式。首先构建基本的SQL字符串,然后加载一些测试值
x <- "SELECT * FROM my_db WHERE db_date = '%s' AND (%s);"
d <- as.Date("2019/12/17")
c1 <- c(1, 2)
c2 <- c(50)
c3 <- c(50, 142, 65, 66)
> sprintf(x, format(d, "%Y/%m/%d"), paste("ItemType =", c1, collapse = " OR "))
[1] "SELECT * FROM my_db WHERE db_date = '2019/12/17' AND (ItemType = 1 OR ItemType = 2);"
> sprintf(x, format(d, "%Y/%m/%d"), paste("ItemType =", c2, collapse = " OR "))
[1] "SELECT * FROM my_db WHERE db_date = '2019/12/17' AND (ItemType = 50);"
> sprintf(x, format(d, "%Y/%m/%d"), paste("ItemType =", c3, collapse = " OR "))
[1] "SELECT * FROM my_db WHERE db_date = '2019/12/17' AND (ItemType = 50 OR ItemType = 142 OR ItemType = 65 OR ItemType = 66);"