Email : sherlytaurinsiri@gmail.com
Instagram : https://www.instagram.com/sherlytaurin
RPubs : https://rpubs.com/sherlytaurin/
Github : https://github.com/sherlytaurin/
Telegram : @Sherlytaurin
Persiapan Awal
Load Packages
Connect ke MySQL
sherly <- dbConnect(MySQL(),
user = 'root',
password = '',
dbname = 'factory_db',
host = 'localhost',
port = 3306)
knitr::opts_chunk$set(connection = "sherly") # mengatur connection agar bisa menggunakan SQL ChunkSELECT C.CustomerID, C.CustomerName, OD.Quantity*P.Price as 'TotalAmount'
FROM customers C
JOIN orders O
ON C.CustomerID = O.CustomerID
JOIN orderdetails OD
ON O.OrderID = OD.OrderID
JOIN products P
ON OD.ProductID = P.ProductID
WHERE OD.Quantity*P.Price > ALL (
SELECT AVG(OD.Quantity*P.Price)
FROM customers C
JOIN orders O
ON C.CustomerID = O.CustomerID
JOIN orderdetails OD
ON O.OrderID = OD.OrderID
JOIN products P
ON OD.ProductID = P.ProductID
GROUP BY c.CustomerID
)
SELECT Country, ProductName, MAX(Revenue) AS 'Revenue'
FROM(SELECT P.ProductName, C.Country, SUM(OD.Quantity*P.Price) AS 'Revenue'
FROM products P
JOIN orderdetails OD
ON P.ProductID = OD.ProductID
JOIN orders O
ON OD.OrderID = O.OrderID
JOIN customers C
ON O.CustomerID = C.CustomerID
GROUP BY C.Country, P.ProductName
ORDER BY Country ASC, Revenue DESC) S
GROUP BY Country
ORDER BY Country;(SELECT P.ProductName, YEAR(O.OrderDate) AS 'Year', sum(OD.Quantity) AS 'Quantity'
FROM products P
JOIN orderdetails OD
ON P.ProductID = OD.ProductID
JOIN orders O
ON OD.OrderID = O.OrderID
GROUP BY Year, ProductName
HAVING Year = 1996
ORDER BY Year, Quantity DESC
LIMIT 10)
UNION
(SELECT P.ProductName, YEAR(O.OrderDate) AS 'Year', sum(OD.Quantity) AS 'Quantity'
FROM products P
JOIN orderdetails OD
ON P.ProductID = OD.ProductID
JOIN orders O
ON OD.OrderID = O.OrderID
GROUP BY Year, ProductName
HAVING Year = 1997
ORDER BY Year, Quantity DESC
LIMIT 10)