I have a query
library(DBI)
res = dbSendQuery(con,
"select
X, Y, z from table where date between date'2018-07-01' - interval '31' day and date'2018-07-01 - interval '1' day")
res.df = dbFetch(res, -1)
I want to run this on a date loop so that it populates the data for all dates between 2018-07-01 and 2018-07-30
Can someone please help me with the code for that
A loop isn't necessary to populate the data for all dates between 2018-07-01 and 2018-07-30.
You can just filter by dates:
res = dbSendQuery(con,
"select X, Y, z
from table
where date > '2018-06-31'
and date < '2018-07-31'")
res.df = dbFetch(res, -1)
If you really want a loop:
date_seq <- as.character(seq(as.Date("2017-07-01"),
as.Date("2017-07-30"), by = "day"))
for (i in 1:length(date_seq)) {
string <- "select X, Y, z from table where date between date'REPLACEME' - interval '31' day and date'REPLACEME' - interval '1' day"
string <- gsub("REPLACEME", date_seq[i], string)
print(string) # replace this with the dbSendQuery
}
[1] "select X, Y, z from table where date between date'2017-07-01' - interval '31' day and date'2017-07-01' - interval '1' day"
[1] "select X, Y, z from table where date between date'2017-07-02' - interval '31' day and date'2017-07-02' - interval '1' day"
...
[1] "select X, Y, z from table where date between date'2017-07-30' - interval '31' day and date'2017-07-30' - interval '1' day"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.