RStudio 操作MySQL数据库
Rstudio 操作mysql实现行转列
# 加载类库
require(RMySQL)
library(RMySQL)
# 建立本地连接
con<-dbConnect(MySQL(),host='xxxx',port=xxx,dbname="xx",user="xx",password="xxxx")
# 修改编码 , 否则会出现中文乱码
dbSendQuery(con, "SET NAMES gbk")
# 查看数据表
dbListTables(con)
# 查看表字段
dbListFields(con, "xx")
# 查询MySQL信息
summary(MySQL(), verbose = TRUE)
# mysql 连接示例信息
summary(con, verbose = TRUE)
# MySQL链接信息
dbListConnections(MySQL())
# 数据查询
# 编辑查询语句
query_0 = "select
a.point_name
,a.monitor_time
,a.pm25
from xx a
where a.region_code='xx'
and DATE_FORMAT(a.monitor_time,'%Y%m')='201811'
GROUP BY a.monitor_time
ORDER BY a.monitor_time;"
# 转置
query_1="select
a.monitor_time as mon_time
,MAX(case a.point_name WHEN '开封' then a.pm25 else 0 END) '开封'
,MAX(case a.point_name WHEN '妇幼保健院' then a.pm25 else 0 END) '妇幼保健院'
,MAX(case a.point_name WHEN '龙亭公园' then a.pm25 else 0 END) '龙亭公园'
,MAX(case a.point_name WHEN '世纪星幼儿园' then a.pm25 else 0 END) '世纪星幼儿园'
,MAX(case a.point_name WHEN '肿瘤医院' then a.pm25 else 0 END) '肿瘤医院'
from xx a
where a.region_code='xx'
and DATE_FORMAT(a.monitor_time,'%Y%m')='201811'
GROUP BY a.monitor_time
ORDER BY a.monitor_time;"
# 执行查询
d0 <- dbGetQuery(con, query_1)
# 关闭连接
dbDisconnect(con)
原数据输出

目标结果输出


浙公网安备 33010602011771号