library(RPostgreSQL)
## Loading required package: DBI
library(sf)
## Linking to GEOS 3.5.1, GDAL 2.1.2, PROJ 4.9.3
library(mapview)
library(leaflet.minicharts)
 drv <- dbDriver("PostgreSQL")

con<-dbConnect(drv, dbname = "clima2",host="postgis",user="docker",password="docker")

ethiopia<-st_read(con, query="select gid,geom from countries where names like 'ETHIOPIA'")

grat<- st_read(con, query="select g.gid, g.geom from graticule g,
(select * from countries where names like 'ETHIOPIA') s
where st_intersects(s.geom,g.geom)")

prec<-dbGetQuery(con, "select p.* from global_monthly_prec p,
(select g.gid from graticule g,
(select * from countries where names like 'ETHIOPIA') s
where st_intersects(s.geom,g.geom)) gids
where gids.gid=p.gid
")
dbDisconnect(con)
## [1] TRUE