-
Notifications
You must be signed in to change notification settings - Fork 3
/
StartSQL.R
58 lines (42 loc) · 1.7 KB
/
StartSQL.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#Ensure odbc library is installed. If it is not, enter install.packages("odbc") in RStudio console.
library(odbc)
odbcListDataSources()
cnxn <- dbConnect(odbc(), server="brkressql01.database.windows.net",
driver = "SQL Server",
database="BRKRes01",
UID = "<your username>",
PWD = "<your password>")
head(dbListTables(cnxn)) # Show available tables
dbListFields(cnxn,'Cars') # Show fields in Cars
D <- dbGetQuery(cnxn, "select * from Cars")
res <- dbSendQuery(cnxn, 'select * from Cars')
d <- dbFetch(res)
# See cash flows from US to India
query <- "SELECT YEAR, SUM(Value) AS Total
FROM CRS1
WHERE
CRS1.DONOR IN (SELECT DONOR FROM Donors WHERE DDescription='United States') AND
CRS1.RECIPIENT IN (SELECT RECIPIENT FROM Recipients WHERE RDescription='India') AND
CRS1.SECTOR IN (SELECT SECTOR from Sectors WHERE SDescription='Total All Sectors')"
rs <- dbSendQuery(cnxn, query)
dat <- list()
i <- 0
while(!dbHasCompleted(rs)){
i <- i+1
dat[[i]] <- dbFetch(rs, n = 100)
}
final_dat <- do.call(rbind, dat)
dbClearResult(rs)
# Using the tidyverse -----------------------------------------------------
library(tidyverse)
crs <- tbl(cnxn,'CRS1')
donors <- tbl(cnxn, 'Donors')
recipients <- tbl(cnxn, 'Recipients')
sectors <- tbl(cnxn, 'Sectors')
D <- crs %>%
semi_join(filter(donors, DDescription=='United States'),by='DONOR') %>%
semi_join(filter(recipients, RDescription=='India'), by='RECIPIENT') %>%
semi_join(filter(sectors, SDescription=='Total All Sectors'), by='SECTOR') %>%
collect(n = Inf)
D %>% group_by(YEAR) %>% summarize(Total = sum(Value)) %>% arrange(YEAR)
dbDisconnect(cnxn)