我有一些要在R环境中调用的PostgreSQL / PostGIS tablefunc查询。有什么方法可以执行此操作?
Ex:
dbGetQuery(con, "SELECT * FROM CROSSTAB(
'SELECT factor1, factor2, ROUND(SUM(ST_AREA(geom))::numeric, 3) FROM table GROUP BY factor1, factor2 ORDER BY 1,2',
'SELECT factor2 FROM table GROUP BY factor2 ORDER BY factor2 '
) AS ct("factor1" varchar, "factor2value1" varchar, "factor2value2" varchar, "factor2value3" varchar)
")
答案 0 :(得分:0)
如果您成功连接到Postgres,则任何兼容的Postgres查询都可以使用。因此,如果一条SQL语句可在Postgres(即psql,pgAdmin)中工作,则它应在与R相连的客户端(如R)中工作。注意:crosstab
需要扩展名。只需在SQL语句中用反斜杠转义双引号即可将其编译为R中的字符:
sql <- "SELECT *
FROM CROSSTAB(
'SELECT factor1, factor2,
ROUND(SUM(ST_AREA(geom))::numeric, 3)
FROM table
GROUP BY factor1, factor2
ORDER BY 1,2'
,
'SELECT factor2
FROM table
GROUP BY factor2
ORDER BY factor2 '
) AS ct(\"factor1\" varchar, \"factor2value1\" varchar,
\"factor2value2\" varchar, \"factor2value3\" varchar)"
dbGetQuery(con, sql)