将字符转换为类日期

时间:2014-01-30 16:55:33

标签: sql r

我有这个查询

sql <- "select 
    observationid::text,id,date, ST_X(location::geometry) as lon, ST_Y(location::geometry) as lat
    from test
    where date>=  '1850-01-01' and date  <'1851-01-01'"
datain<-dbGetQuery(dbh,sql)

我从R运行。我想要做的是在查询之外设置日期范围,例如

datamin <- '1850-01-01'
datamax <- '1851-01-01'
sql <- "select 
    observationid::text,id,date, ST_X(location::geometry) as lon, ST_Y(location::geometry) as lat
    from test
    where date>=  datamin and date  <datamax"
datain<-dbGetQuery(dbh,sql)

但我收到此错误

Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not Retrieve the result : ERROR:  column "datamin" does not exist

非常感谢

2 个答案:

答案 0 :(得分:0)

您需要将datamin和datamax编码为日期:

datamin <- as.Date('1850-01-01')
datamax <- as.Date('1851-01-01')

答案 1 :(得分:0)

datamin <- '1850-01-01'
datamax <- '1851-01-01'

sql <- sprintf("select 
        observationid::text,id,date, ST_X(location::geometry) as lon, ST_Y(location::geometry) as lat
        from test
        where date>= '%s' and date < '%s';",datamin,datamax)
datain<-dbGetQuery(dbh,sql)