forked from smithjd/sql-pet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
155-sql-joins-exercises-with-answers.Rmd
2205 lines (1779 loc) · 84.2 KB
/
155-sql-joins-exercises-with-answers.Rmd
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
output:
html_document:
code_folding: "hide"
---
# SQL Joins Exercises Answered {#chapter_sql-joins-exercises-answered}
> This chapter contains questions one may be curious about or asked about the DVD Rental business.
> The goal of the exercises is extracting useful or questionable insights from one or more tables. Each exercise has has some or all of the following parts.
> 1. The question.
> 2. The tables used to answer the question.
> 3. A hidden SQL code block showing the desired output. Click the code button to see the SQL code.
> 4. A table of derived values or renamed columns shown in the SQL block to facilitate replicating the desired dplyr solution. Abbreviated column names are used to squeeze in more columns into the answer to reduce scrolling across the screen.
> 5. A replication section where you recreate the desired output using dplyr syntax. Most columns come directly out of the tables. Each replication code block has three commented function calls
> * sp_tbl_descr('store') --describes a table, store
> * sp_tbl_pk_fk('table_name') --shows a table's primary and foreign keys
> * sp_print_df(table_rows_sql) --shows table row counts.
>
> 6. To keep the exercises concentrated on the joins, all derived dates drop their timestamp.
> * SQL syntax: date_column::DATE
> * Dplyr syntax: as.date(date_colun)
## Exercise Instructions
1. Manually execute all the code blocks up-to the "SQL Union Exercise."
2. Most of the exercises can be performed in any order.
* There are function exercises that create a function followed by another code block to call the function in the previous exercise.
3. Use the Show Document Outline, CTL-Shift-O, to navigate to the different exercises.
```{r setup, echo=FALSE, message=FALSE, warning=FALSE}
# These packages are called in almost every chapter of the book:
library(tidyverse)
library(DBI)
library(RPostgres)
library(glue)
library(here)
require(knitr)
library(dbplyr)
library(sqlpetr)
```
```{r codeblock options,echo=FALSE}
ECHO_CODE_BLOCK = TRUE
HEAD_N = 10 #set to 0 for all rows or head(x,n=HEAD_N)
INCLUDE_OUTPUT = TRUE
```
Verify Docker is up and running:
```{r}
sp_check_that_docker_is_up()
```
Verify pet DB is available, it may be stopped.
```{r}
sp_show_all_docker_containers()
```
Start up the `docker-pet` container
```{r}
sp_docker_start("sql-pet")
```
Now connect to the database with R
```{r}
# need to wait for Docker & Postgres to come up before connecting.
con <- sp_get_postgres_connection(
user = Sys.getenv("DEFAULT_POSTGRES_USER_NAME"),
password = Sys.getenv("DEFAULT_POSTGRES_PASSWORD"),
dbname = "dvdrental",
seconds_to_test = 30, connection_tab = TRUE
)
```
## Dplyr tables
All the tables defined in the DVD Rental System will fit into memory which is rarely the case when working with a database. Instead of loading all the DVD Rental System tables into memory via a DBI::dbReadTable, each table is loaded into an R object named TableName_table, via a dplyr::tbl call.
* actor_table <- dplyr::tbl(con,"actor")
```{r Declare Dplyr Tables}
source(here('book-src','dvdrental-table-declarations.R'), echo = FALSE)
```
The key difference between the DBI::dbTableRead and the dplyr::tbl reference is the first is `not lazy` and the second one is `lazy`.
The following code block deletes and inserts records into the different tables used in the exercises in this chpater. The techniques used in this code block are discussed in detail in the appendix, ??add link here.??
```{r collapse=TRUE}
source(file=here::here('book-src','sql_pet_data.R'),echo=FALSE)
```
## Oveview Exercise
When joining many tables, it is helpful to have the number of rows from each table as an initial sanity check that the joins are returning a reasonable number of rows.
### 1. How many rows are in each table?
```{r sql union, code_folding='unhide',echo=ECHO_CODE_BLOCK, tidy=TRUE}
table_rows_sql <- dbGetQuery(con, "select *
from ( select 'actor' tbl_name,count(*) from actor
union select 'category' tbl_name,count(*) from category
union select 'film' tbl_name,count(*) from film
union select 'film_actor' tbl_name,count(*) from film_actor
union select 'film_category' tbl_name,count(*) from film_category
union select 'language' tbl_name,count(*) from language
union select 'inventory' tbl_name,count(*) from inventory
union select 'rental' tbl_name,count(*) from rental
union select 'payment' tbl_name,count(*) from payment
union select 'staff' tbl_name,count(*) from staff
union select 'customer' tbl_name,count(*) from customer
union select 'address' tbl_name,count(*) from address
union select 'city' tbl_name,count(*) from city
union select 'country' tbl_name,count(*) from country
union select 'store' tbl_name,count(*) from store
) counts
order by tbl_name
;
")
sp_print_df(table_rows_sql)
```
#### Replicate the output above using dplyr syntax.
```{r dplyr union, include=INCLUDE_OUTPUT,echo=ECHO_CODE_BLOCK}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
table_rows_dplyr <-
as.data.frame(actor_table %>% mutate(name = "actor") %>% group_by(name) %>%
summarize(rows = n())) %>%
union(as.data.frame(address_table %>% mutate(name = "address") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union (as.data.frame(category_table %>% mutate(name = "category") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(country_table %>% mutate(name = "city") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(country_table %>% mutate(name = "country") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(customer_table %>% mutate(name = "customer") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(film_table %>% mutate(name = "film") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(film_actor_table %>% mutate(name = "film_actor") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(film_category_table %>% mutate(name = "film_category") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(inventory_table %>% mutate(name = "inventory") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(language_table %>% mutate(name = "language") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(rental_table %>% mutate(name = "rental") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(payment_table %>% mutate(name = "payment") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(staff_table %>% mutate(name = "staff") %>% group_by(name) %>%
summarize(rows = n()))) %>%
union(as.data.frame(store_table %>% mutate(name = "store") %>% group_by(name) %>%
summarize(rows = n()))) %>%
arrange(name)
sp_print_df(table_rows_dplyr)
```
## Exercises
### 1. Where is the DVD Rental Business located?
To answer this question we look at the `store`, `address`, `city`, and `country` tables to answer this question.
```{r ex1-s, code_folding='unhide', tidy=TRUE}
store_locations_sql <- dbGetQuery(con,
"select s.store_id
,a.address
,c.city
,a.district
,a.postal_code
,c2.country
,s.last_update
from store s
join address a on s.address_id = a.address_id
join city c on a.city_id = c.city_id
join country c2 on c.country_id = c2.country_id
")
sp_print_df(store_locations_sql)
```
`r sp_color_markdown_text("Our DVD Rental business is international and operates in three countries, Canada, Austraila, and the United States. Each country has one store.","blue")`
#### Replicate the output above using dplyr syntax.
```{r ex1-d, include=INCLUDE_OUTPUT, tidy=TRUE }
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
store_locations_dplyr <- store_table %>%
inner_join(address_table, by = c("address_id" = "address_id"), suffix(c(".s", ".a"))) %>%
inner_join(city_table, by = c("city_id" = "city_id"), suffix(c(".a", ".c"))) %>%
inner_join(country_table, by = c("country_id" = "country_id"), suffix(c(".a", ".c"))) %>%
select (store_id,address,city,district,postal_code,country,last_update.x) %>%
collect()
sp_print_df(store_locations_dplyr)
```
### 2. List each store and the staff contact information?
To answer this question we look at the `store`, `staff`, `address`, `city`, and `country` tables.
```{r ex2-s, code_folding='unhide', tidy=TRUE}
store_employees_sql <- dbGetQuery(con,
"select st.store_id
,s.first_name
,s.last_name
,s.email
,a.phone
,a.address
,c.city
,a.district
,a.postal_code
,c2.country
from store st left join staff s on st.manager_staff_id = s.staff_id
left join address a on s.address_id = a.address_id
left join city c on a.city_id = c.city_id
left join country c2 on c.country_id = c2.country_id
")
sp_print_df(store_employees_sql)
```
`r sp_color_markdown_text("Our DVD Rental business is international and operates in three countries, Canada, Austraila, and the United States. Each country has one store. The stores in Canada and Austrailia have one employee each, Mike Hillyer and Jon Stephens respectively. The store in the United States has no employees yet.","blue")`
#### Replicate the output above using dplyr syntax.
```{r ex2-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
store_employees_dplyr <- store_table %>%
left_join (staff_table, by = c("manager_staff_id" = "staff_id"),suffix(c('sto','sta'))) %>%
left_join(address_table, by = c("address_id.y" = "address_id"), suffix(c(".sta", ".a"))) %>%
left_join(city_table, by = c("city_id" = "city_id"), suffix(c(".sta", ".city"))) %>%
left_join(country_table, by = c("country_id" = "country_id"), suffix(c(".city", ".cnt"))) %>%
select(store_id.x,first_name,last_name,email,phone,address,city,district,postal_code,country) %>%
collect()
sp_print_df(store_employees_dplyr)
```
### 3. How many active, inactive, and total customers does the DVD rental business have?
To answer this question we look at the `customer` table. In a previous chapter we observed that there are two columns, `activebool` and `active`. We consider `active = 1` as active.
```{r ex3-s, code_folding='unhide', tidy=TRUE}
customer_cnt_sql <- dbGetQuery(con,
"SELECT sum(case when active = 1 then 1 else 0 end) active
,sum(case when active = 0 then 1 else 0 end) inactive
,count(*) total
from customer
")
sp_print_df(customer_cnt_sql)
```
`r sp_color_markdown_text('
Our DVD Rental business is international and operates in three countries, Canada, Austraila, and the United States. Each country has one store. The stores in Canada and Austrailia have one employee each. The store in the United States has no employees yet.
The business has 604 international customers, 589 are active and 15 inactive.','blue')`
#### Replicate the output above using dplyr syntax.
```{r ex3-d, include=INCLUDE_OUTPUT, tidy=TRUE}
customer_cnt_dplyr <- customer_table %>%
mutate(inactive = ifelse(active==0,1,0)) %>%
summarize(active = sum(active)
,inactive = sum(inactive)
,total = n()
) %>%
collect()
sp_print_df(customer_cnt_dplyr)
```
### 4. How many and what percent of customers are from each country?
To answer this question we look at the `customer`, `address`, `city`, and `country` tables.
```{r ex4-s, code_folding='unhide', tidy=TRUE}
customers_sql <- dbGetQuery(con,
"select c.active,country.country,count(*) count
,round(100 * count(*) / sum(count(*)) over(),4) as pct
from customer c
join address a on c.address_id = a.address_id
join city on a.city_id = city.city_id
join country on city.country_id = country.country_id
group by c.active,country
order by count(*) desc
")
sp_print_df(customers_sql)
```
`r sp_color_markdown_text('
Based on the table above, the DVD Rental business has customers in 118 countries. The DVD Rental business cannot have many walk in customers. It may possibly use a mail order distribution model.
For an international company, how are the different currencies converted to a standard currency? Looking at the ERD, there is no currency conversion rate.','blue')`
#### Replicate the output above using dplyr syntax.
> The following snippet of code fails.
```{r ex4-d, include=INCLUDE_OUTPUT, eval=FALSE, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
cust_cnt <- customer_table %>% summarize(rows=n()) %>% collect()
customers_dplyr <- customer_table %>%
inner_join(address_table, by = c("address_id" = "address_id"), suffix(c(".s", ".a"))) %>%
inner_join(city_table, by = c("city_id" = "city_id"), suffix(c(".a", ".c"))) %>%
inner_join(country_table, by = c("country_id" = "country_id"), suffix(c(".a", ".c"))) %>%
group_by(active,country) %>%
summarize(count=n()) %>%
mutate(total=cust_cnt$rows # nrow(customer_table)
,pct=round(100 * count/total,4)
) %>%
arrange(desc(count)) %>%
select (active,country,count,pct) %>%
collect()
sp_print_df(customers_dplyr)
```
### 5. What countries constitute the top 25% of the customer base?
Using the previous code, add two new columns. One column shows a running total and the second column shows a running percentage. Order the data by count then by country.
To answer this question we look at the `customer`, `address`, `city`, and `country` tables again.
```{r ex5-s, code_folding='unhide', tidy=TRUE}
country_sql <- dbGetQuery(con,
"select active,country,count
,sum(count) over (order by count desc,country rows between unbounded preceding and current row) running_total
, pct
,sum(pct) over (order by pct desc,country rows between unbounded preceding and current row) running_pct
from (-- Start of inner SQL Block
select c.active,country.country,count(*) count
,round(100 * count(*) / sum(count(*)) over(),4) as pct
from customer c
join address a on c.address_id = a.address_id
join city on a.city_id = city.city_id
join country on city.country_id = country.country_id
group by c.active,country
) ctry -- End of inner SQL Block
order by count desc,country
")
sp_print_df(country_sql)
```
`r sp_color_markdown_text('
The top 25% of the customer base are from India, China, the United States, and Japan. The next six countries, the top 10, Mexico, Brazil, Russian Federation, Philipines, Indonesia, and Turkey round out the top 50% of the businesses customer base.','blue')`
#### Replicate the output above using dplyr syntax.
```{r ex5-d, include=INCLUDE_OUTPUT, eval=FALSE, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
cust_cnt <- customer_table %>% summarize(rows=n()) %>% collect()
country_dplyr <- customer_table %>%
inner_join(address_table, by = c("address_id" = "address_id"), suffix(c(".s", ".a"))) %>%
inner_join(city_table, by = c("city_id" = "city_id"), suffix(c(".a", ".c"))) %>%
inner_join(country_table, by = c("country_id" = "country_id"), suffix(c(".a", ".c"))) %>%
group_by(active,country) %>%
summarize(count=n()) %>%
mutate(total=cust_cnt$rows
,pct=round(100 * count/total,4)
,csp=1
) %>%
arrange(desc(count)) %>%
group_by(csp) %>%
mutate(running_pct=cumsum(pct)
,running_total=cumsum(count)) %>%
select (csp,active,country,count,running_total,pct,running_pct) %>%
collect()
sp_print_df(country_dplyr)
```
### 6. How many customers are in Australia and Canada?
To answer this question we use the results from the previous exercise.
```{r ex6-s, code_folding='unhide', tidy=TRUE}
country_au_ca_sql <- country_sql %>% filter(country == 'Australia' | country == 'Canada')
sp_print_df(country_au_ca_sql)
```
`r sp_color_markdown_text("There are 10 customers in Austrailia and Canada where the brick and mortar stores are located. The 20 customers are less than 2% of the world wide customer base. ",'blue')`
#### Replicate the output above using dplyr syntax.
> The following code fails:
```{r ex6-d, include=INCLUDE_OUTPUT, eval=FALSE, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
country_au_ca_dplyr <- country_dplyr %>% filter(country == 'Australia' | country == 'Canada')
sp_print_df(country_au_ca_dplyr)
```
### 7. How many languages?
With an international customer base, how many languages does the DVD Rental business distribute DVD's in.
To answer this question we look at the `language` table.
```{r ex7-s, code_folding='unhide', tidy=TRUE}
languages_sql <- dbGetQuery(con,
"
select * from language
")
sp_print_df(languages_sql)
```
`r sp_color_markdown_text("DVD's are distributed in six languages.","blue")`
#### Replicate the output above using dplyr syntax.
```{r ex7-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
languages_dplyr <- language_table %>% collect()
sp_print_df(languages_dplyr)
```
### 8. What is the distribution of DVD's by Language
To answer this question we look at the `language` and `film` tables.
```{r ex8-s, code_folding='unhide', tidy=TRUE}
language_distribution_sql <- dbGetQuery(con,
'
select l.language_id,name "language",count(f.film_id)
from language l left join film f on l.language_id = f.language_id
group by l.language_id,name
order by l.language_id
')
sp_print_df(language_distribution_sql)
```
`r sp_color_markdown_text("This is a surprise. For an international customer base, the entire stock of 1001 DVD's are in English only.",'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex8-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
language_distribution_dplyr <- language_table %>%
left_join(film_table, by = c("language_id" = "language_id"), suffix(c(".s", ".a"))) %>%
group_by(language_id,name) %>%
summarize(count = sum(ifelse(!is.na(title),1,0)),na.rm=TRUE) %>%
collect()
sp_print_df(language_distribution_dplyr)
```
### 9. What are the number of rentals and rented amount by store, by month?
To answer this question we look at the `rental`, `inventory`, and `film` tables to answer this question.
```{r ex9-s, code_folding='unhide', tidy=TRUE}
store_rentals_by_mth_sql <- dbGetQuery(con,
"select *
,sum(rental_amt) over (order by yyyy_mm,store_id rows
between unbounded preceding and current row) running_rental_amt
from (select yyyy_mm,store_id,rentals,rental_amt
,sum(rentals) over(partition by yyyy_mm order by store_id) mo_rentals
,sum(rental_amt) over (partition by yyyy_mm order by store_id) mo_rental_amt
from (select to_char(rental_date,'yyyy-mm') yyyy_mm
,i.store_id,count(*) rentals, sum(f.rental_rate) rental_amt
from rental r join inventory i on r.inventory_id = i.inventory_id
join film f on i.film_id = f.film_id
group by to_char(rental_date,'yyyy-mm'),i.store_id
) as details
) as mo_running
order by yyyy_mm,store_id
")
sp_print_df(store_rentals_by_mth_sql)
```
`r sp_color_markdown_text("The current entry, row 11, is our new rental row we added to show the different joins in a previous chapter.
",'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex9-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
store_rentals_by_mth_dplyr <- rental_table %>%
inner_join(inventory_table, by = c("inventory_id" = "inventory_id"), suffix(c(".r", ".i"))) %>%
inner_join(film_table, by = c("film_id" = "film_id"), suffix(c(".i", ".f"))) %>%
mutate(YYYY_MM = to_char(rental_date,"YYYY-MM")
,running_total = 'running_total'
) %>%
group_by(running_total,YYYY_MM,store_id) %>%
summarise(rentals = n()
,rental_amt = sum(rental_rate,na.rm = TRUE)
) %>%
mutate(mo_rentals=order_by(store_id,cumsum(rentals))
,mo_rental_amt=order_by(store_id,cumsum(rental_amt))
) %>%
group_by(running_total) %>%
arrange(YYYY_MM,store_id) %>%
mutate(running_rental_amt = cumsum(rental_amt)) %>%
select(-running_total) %>%
collect()
sp_print_df(head(store_rentals_by_mth_dplyr, n=25))
```
### 10. Rank films based on the number of times rented and associated revenue
To answer this question we look at the `rental`, `inventory`, and `film` tables.
```{r ex10-s, code_folding='unhide', tidy=TRUE}
film_rank_sql <- dbGetQuery(con,
"select f.film_id,f.title,f.rental_rate,count(*) count,f.rental_rate * count(*) rental_amt
from rental r join inventory i on r.inventory_id = i.inventory_id
join film f on i.film_id = f.film_id
group by f.film_id,f.title,f.rental_rate
order by count(*) desc")
sp_print_df(film_rank_sql)
```
`r sp_color_markdown_text("The most frequently rented movie, 34 times, is 'Bucket Brotherhood' followed by Rocketeer Mother, 33 times.",'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex10-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
film_rank_dplyr <- rental_table %>%
inner_join(inventory_table, by = c("inventory_id" = "inventory_id"), suffix(c(".r", ".i"))) %>%
inner_join(film_table, by = c("film_id" = "film_id"), suffix(c(".f", ".i"))) %>%
group_by(film_id,title,rental_rate) %>%
summarize(count = n()
,rental_amt = sum(rental_rate)
) %>%
arrange(desc(count)) %>%
collect()
sp_print_df(film_rank_dplyr)
```
### 11. What is the rental distribution/DVD for the top two rented films?
From the previous exercise we know that the top two films are `Bucket Brotherhood` and `Rocketeer Mother`.
To answer this question we look at the `rental`, `inventory`, and `film` tables again.
Instead of looking at the film level, we need to drill down to the individual dvd's for each film to answer this question.
```{r ex11-s, code_folding='unhide', tidy=TRUE}
film_rank2_sql <- dbGetQuery(con,
"select i.store_id,i.film_id,f.title,i.inventory_id,count(*)
from rental r join inventory i on r.inventory_id = i.inventory_id
join film f on i.film_id = f.film_id
where i.film_id in (103,738)
group by i.store_id,i.film_id,f.title,i.inventory_id")
sp_print_df(film_rank2_sql)
```
`r sp_color_markdown_text("The 'Bucket Brotherhood' and 'Rocketeer Mother' DVD's are equally distributed between the two stores, 4 dvd's each per film. The 'Bucket Brotherhood' was rented 17 times from both stores. The 'Rocketeer Mother' was rented 15 times from store 1 and 18 times from store 2.",'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex11-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
film_rank2_dplyr <- rental_table %>%
inner_join(inventory_table, by = c("inventory_id" = "inventory_id"), suffix(c(".r", ".i"))) %>%
inner_join(film_table, by = c("film_id" = "film_id"), suffix(c(".f", ".i"))) %>%
filter(film_id %in% c(103,738)) %>%
group_by(store_id,film_id,title,inventory_id) %>%
summarize(count = n()) %>%
arrange(film_id,store_id,inventory_id) %>%
collect()
sp_print_df(film_rank2_dplyr)
```
### 12. List staffing information for store 1 associated with the `Bucket Brother` rentals?
To answer this question we look at the `rental`, `inventory`, `film`, `staff`, `address`, `city`, and `country` tables.
```{r ex12-s, code_folding='unhide', tidy=TRUE}
film_103_details_sql <- dbGetQuery(con,
"select i.store_id,i.film_id,f.title,i.inventory_id inv_id,i.store_id inv_store_id
,r.rental_date::date rented,r.return_date::date returned
,s.staff_id,s.store_id staff_store_id,concat(s.first_name,' ',s.last_name) staff,ctry.country
from rental r join inventory i on r.inventory_id = i.inventory_id
join film f on i.film_id = f.film_id
join staff s on r.staff_id = s.staff_id
join address a on s.address_id = a.address_id
join city c on a.city_id = c.city_id
join country ctry on c.country_id = ctry.country_id
where i.film_id in (103)
and r.rental_date::date between '2005-05-01'::date and '2005-06-01'::date
order by r.rental_date
")
sp_print_df(film_103_details_sql)
```
`r sp_color_markdown_text("In a previous exercise we saw that store 1 based in Canada and store 2 based in Austrailia each had one employee, staff_id 1 and 2 respectively. We see that Mike from store 1, Canada, had transactions in store 1 and store 2 on 5/25/2005. Similarly Jon from store 2, Australia, had transaction in store 2 and store 1 on 5/31/2005. Is this phsically possible, or a key in error?"
,'blue')`
#### Replicate the output above using dplyr syntax.
column | mapping |definition
---------------|-----------------------|-----------
inv_id |inventory.inventory_id |
inv_store_id |inventory.store_id |
rented |rental.rental_date |
returned |rental.return_date |
staff_store_id |store.store_id |
staff |first_name+last_name |
```{r ex12-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
film_103_details_dplyr <- inventory_table %>% filter(film_id == 103) %>%
inner_join(film_table, by=c('film_id' = 'film_id'),suffix(c('.f','r'))) %>%
inner_join(rental_table, by=c('inventory_id' = 'inventory_id'),suffix(c('.i','r'))) %>%
filter(rental_date < '2005-06-01') %>%
inner_join(staff_table, by=c('staff_id' = 'staff_id'),suffix(c('.x','r'))) %>%
inner_join(address_table, by=c('address_id' = 'address_id'),suffix(c('.a','r'))) %>%
inner_join(city_table, by=c('city_id' = 'city_id'),suffix(c('.c','a'))) %>%
inner_join(country_table, by=c('country_id' = 'country_id'),suffix(c('.ctry','city'))) %>%
mutate(rented = Date(rental_date)
,returned = Date(return_date)
,staff = paste0(first_name,' ',last_name)
) %>%
rename(inv_store = store_id.x
,staff_store_id=store_id.y
,inv_id = inventory_id
) %>%
select(inv_store,film_id,title,inv_id,rented,returned,staff_id,staff_store_id
,staff,country) %>%
arrange(rented) %>%
collect()
sp_print_df(film_103_details_dplyr)
```
### 13. Which film(s) have never been rented
To answer this question we look at the `film`, `inventory` and `rental` tables.
```{r ex13-s, code_folding='unhide', tidy=TRUE}
never_rented_dvds_sql <- dbGetQuery(con,
'select i.store_id,f.film_id, f.title,f.description, i.inventory_id
from film f join inventory i on f.film_id = i.film_id
left join rental r on i.inventory_id = r.inventory_id
where r.inventory_id is null
'
)
sp_print_df(never_rented_dvds_sql)
```
`r sp_color_markdown_text("There are only two movies that have not been rented, Academy Dinousaur and Sophie's Choice."
,'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex13-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
never_rented_dvds_dplyr <- film_table %>%
inner_join(inventory_table, by = c("film_id" = "film_id"), suffix(c(".f", ".i"))) %>%
anti_join(rental_table, by = c('inventory_id','inventory_id'), suffix(c('.i','.r'))) %>%
select(film_id,title,description,inventory_id) %>%
collect()
sp_print_df(never_rented_dvds_dplyr)
```
### 14. How many films are in each film rating?
To answer this question we look at the `film` table to answer this question.
```{r ex14-s, code_folding='unhide', tidy=TRUE}
film_ratings_sql <- dbGetQuery(con,
'select f.rating,count(*)
from film f
group by f.rating
order by count(*) desc
'
)
sp_print_df(film_ratings_sql)
```
`r sp_color_markdown_text("There are 5 ratings and all 5 have roughly 200 movies."
,'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex14-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
film_ratings_dplyr <- film_table %>%
group_by(rating) %>%
summarize(count=n()) %>%
arrange(desc(count)) %>%
collect()
sp_print_df(film_ratings_dplyr)
```
### 15. What are the different film categories?
To answer this question we look at the `category` table to answer this question.
```{r ex15-s, code_folding='unhide', tidy=TRUE}
film_categories_sql <- dbGetQuery(con,
'select * from category'
)
sp_print_df(film_categories_sql)
```
`r sp_color_markdown_text("There are 16 different categories","blue")`
#### Replicate the output above using dplyr syntax.
```{r ex15-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
film_categories_dplyr <- category_table %>%
collect()
sp_print_df(film_categories_dplyr)
```
### 16. How many DVD's are in each film categeory?
To answer this question we look at the `category` table again.
```{r ex16-s, code_folding='unhide', tidy=TRUE}
film_categories2_sql <- dbGetQuery(con,
'select c.name,count(*) count
from category c join film_category fc on c.category_id = fc.category_id
group by c.name
order by count(*) desc
'
)
sp_print_df(film_categories2_sql)
```
`r sp_color_markdown_text('There are 16 film categories. The highest category, Sports, has 77 films followed by the International category which has 76 film. What is an example of an international category film where all films are currently in English?','blue')`
#### Replicate the output above using dplyr syntax.
```{r ex16-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
film_categories2_dplyr <- category_table %>%
inner_join(film_category_table, by =c('category_id'='category_id')
,suffix(c('.c','.fc'))) %>%
group_by(name) %>%
summarise(count=n()) %>%
arrange(desc(count)) %>%
collect()
sp_print_df(film_categories2_dplyr)
```
### 17. Which films are listed in multiple categories?
To answer this question we look at the `film`, `film_category` and `category` tables.
```{r ex17-s, code_folding='unhide', tidy=TRUE}
multiple_categories_sql <- dbGetQuery(con,
'select f.film_id, f.title,c.name
from film_category fc join film f on fc.film_id = f.film_id
join category c on fc.category_id = c.category_id
where fc.film_id in (select fc.film_id
from film f join film_category fc on f.film_id = fc.film_id
group by fc.film_id
having count(*) > 1
)
'
)
sp_print_df(multiple_categories_sql)
```
`r sp_color_markdown_text("There is only one film which has two categories, Sophie's Choice.",'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex17-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
multiple_categories_dplyr <-
# compute films with multiple categories
film_table %>%
inner_join(film_category_table,by=c('film_id'='film_id'), suffix(c('.f','.fc'))) %>%
group_by(film_id,title) %>%
summarise(count=n()) %>%
filter(count > 1) %>%
# get the category ids
inner_join(film_category_table, by = c('film_id'='film_id'),suffix(c('.f','.fc'))) %>%
# get the category names
inner_join(category_table, by=c('category_id'='category_id')) %>%
select(film_id,title,name) %>%
collect()
sp_print_df(multiple_categories_dplyr)
```
### 18. Which DVD's are in one store's inventory but not the other
In the table below we show the first `r HEAD_N` rows.
To answer this question we look at the `inventory` and `film` tables.
```{r ex18-s, code_folding='unhide', tidy=TRUE}
dvd_in_1_store_sql <- dbGetQuery(
con,
"
-- select store1,count(count1) films_not_in_store_2,sum(coalesce(count1,0)) dvds_not_in_store_1
-- ,store2,count(count2) films_not_in_store_1,sum(coalesce(count2,0)) dvds_not_in_store_2
-- from (
select coalesce(i1.film_id,i2.film_id) film_id,f.title,f.rental_rate
,1 store1,coalesce(i1.count,0) count1
,2 store2,coalesce(i2.count,0) count2
-- dvd inventory in store 1
from (select film_id,store_id,count(*) count
from inventory where store_id = 1
group by film_id,store_id
) as i1
full outer join
-- dvd inventory in store 2
(select film_id,store_id,count(*) count
from inventory where store_id = 2
group by film_id,store_id
) as i2
on i1.film_id = i2.film_id
join film f
on coalesce(i1.film_id,i2.film_id) = f.film_id
where i1.film_id is null or i2.film_id is null
order by f.title
-- ) as src
-- group by store1,store2
"
)
if(HEAD_N > 0) {
sp_print_df(head(dvd_in_1_store_sql,n=HEAD_N))
} else {
sp_print_df(dvd_in_1_store_sql)
}
```
`r sp_color_markdown_text("Store 1 has 196 films, (576 dvd's), that are not in store 2. Store 2 has 199 films, (607 dvd's), that are not in store 1.",'blue')`
#### Replicate the output above using dplyr syntax.
> The following code isn't working yet.
```{r ex18-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
inv_tbl1 <- inventory_table %>%
filter(store_id == 1 ) %>%
group_by(film_id) %>%
summarise(count=n())
inv_tbl2 <- inventory_table %>%
filter(store_id == 2 ) %>%
group_by(film_id) %>%
summarise(count=n())
dvd_in_1_store_dplyr <- inv_tbl1 %>%
full_join(inv_tbl2, by=c('film_id','film_id'),suffix(c('.i1','.i2'))) %>%
filter(is.na(count.x) | is.na(count.y)) %>%
# filter(is.na(count.x + count.y)) %>% #this works also
mutate_all(funs(ifelse(is.na(.), 0, .))) %>%
inner_join(film_table,by=c('film_id','film_id'), copy =TRUE) %>%
mutate(store_id1 = 1, store_id2 = 2) %>%
select (film_id,title,rental_rate,store_id1,count.x,store_id2,count.y) %>%
arrange(film_id) %>%
collect()
if(HEAD_N > 0) {
sp_print_df(head(dvd_in_1_store_dplyr,n=HEAD_N))
} else {
sp_print_df(dvd_in_1_store_dplyr)
}
```
### 19. Which films are not tracked in inventory?
To answer this question we look at the `film` and `rental` tables.
```{r ex19-s, code_folding='unhide', tidy=TRUE}
films_no_inventory_sql <- dbGetQuery(con,
"
select f.film_id,title,rating,rental_rate,replacement_cost
from film f left outer join inventory i on f.film_id = i.film_id
where i.film_id is null;
")
if(HEAD_N > 0) {
sp_print_df(head(films_no_inventory_sql,n=HEAD_N))
} else {
sp_print_df(films_no_inventory_sql)
}
```
`r sp_color_markdown_text("There are 42 films that do not exist in inventory or in either store. These may be DVD's that have been ordered but the business has not received them. Looking at the price and the replacement cost, it doesn't look like there is any rhyme or reason to the setting of the price.",'blue')`
#### Replicate the output above using dplyr syntax.
```{r ex19-d, include=INCLUDE_OUTPUT, tidy=TRUE}
# sp_tbl_descr('table_name')
# sp_tbl_pk_fk('table_name')
# sp_print_df(table_rows_sql)
films_no_inventory_dplyr <- film_table %>%
anti_join(inventory_table, by=(c('film_id'='film_id'))) %>%
select (film_id,title,rating,rental_rate,replacement_cost) %>%
collect()
if(HEAD_N > 0) {
sp_print_df(head(films_no_inventory_dplyr,n=HEAD_N))