在R和sqlQuery函数中使用RODBC包从数据库中连接3个表

时间:2016-08-04 11:21:54

标签: sql r rodbc

您能否帮我理解如何使用{{left join master table与另外两个表格x1x2之间创建x3 sqlQuery 1}}函数来自R。

中的RODBC

设置数据库连接后,我成功连接了两个表:

library RODBC

dataframe <-sqlQuery(conn,"
SELECT
sum(A1.revenue1),
sum(A1.revenue2), 
sum(A1.revenue3),
A2.SERVICE_TYPE_NAME
FROM
(FINANCE.x1 A1 LEFT JOIN CORE.x2 A2
ON (A1.YEAR_NUM = A2.YEAR_NUM 
AND A1.SERVICE_TYPE_KEY = A2.SERVICE_TYPE_KEY)
)
WHERE A1.YEAR_NUM = '2015' 
AND A2.SERVICE_TYPE_KEY='2'
GROUP BY A2.SERVICE_TYPE_NAME
")

但是当我试图将第三个试图带到这个等式时我失败了:

dataframe <-sqlQuery(conn,"
SELECT
sum(A1.revenue1),
sum(A1.revenue2), 
sum(A1.revenue3),
A2.SERVICE_TYPE_NAME
FROM
(FINANCE.x1 A1 LEFT JOIN CORE.x2 A2
ON (A1.YEAR_NUM = A2.YEAR_NUM 
AND A1.SERVICE_TYPE_KEY = A2.SERVICE_TYPE_KEY)

FINANCE.x1 A1 LEFT JOIN BRAND.x3
ON (A1.brand_ID=A3.brand_ID))
WHERE A1.YEAR_NUM = '2015' 
AND A2.SERVICE_TYPE_KEY='2'
GROUP BY A2.SERVICE_TYPE_NAME
")

1 个答案:

答案 0 :(得分:1)

您的第二个SQL需要清理。在进行连接时,您只需提及一次表。试试这个:

SELECT SUM(A1.revenue1),
       SUM(A1.revenue2), 
       SUM(A1.revenue3),
       A2.SERVICE_TYPE_NAME
FROM FINANCE.x1 A1
LEFT JOIN CORE.x2 A2
    ON A1.YEAR_NUM = A2.YEAR_NUM AND
       A1.SERVICE_TYPE_KEY = A2.SERVICE_TYPE_KEY
LEFT JOIN BRAND.x3
    ON A1.brand_ID=A3.brand_ID
WHERE A1.YEAR_NUM = '2015' AND
      A2.SERVICE_TYPE_KEY = '2'
GROUP BY A2.SERVICE_TYPE_NAME