can you help me to understand how i can create a left join
between a master table
x1
and two other tables x2
and x3
using the sqlQuery
function from the RODBC
package in R.
After I setup the database connection I successfully can join two tables:
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
")
but I fail when I try to bring a 3rd to the equation trying this:
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
")
Your second SQL needs to be cleaned up. You only mention each table once when doing a join. Try this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.