-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbookSales_long.sql
84 lines (68 loc) · 2.09 KB
/
bookSales_long.sql
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
USE booksales;
SELECT * FROM newsletter;
SELECT * FROM web;
SELECT * FROM store;
--
SELECT UserID, ROUND(SUM(PurchaseAmount),2) AS Purchases_Online, COUNT(PurchaseAmount) AS Visits_Online
FROM web
GROUP BY UserID;
SELECT UserID, ROUND(SUM(PurchaseAmount),2) AS Purchases_Store, COUNT(PurchaseAmount) AS Visits_Store
FROM store
GROUP BY UserID;
--
SELECT UserID, "Online" AS Location, ROUND(SUM(PurchaseAmount),2) AS Purchases, COUNT(PurchaseAmount) AS Visits
FROM web
GROUP BY UserID
UNION
SELECT UserID, "Store" AS Location, ROUND(SUM(PurchaseAmount),2) AS Purchases, COUNT(PurchaseAmount) AS Visits
FROM store
GROUP BY UserID
ORDER BY UserID;
--
SELECT summary.UserID, Location, Purchases, Visits,
CASE
WHEN Newsletter.UserID IS NULL THEN 0
ELSE 1
END AS Newsletter
FROM
(
SELECT UserID, "Online" AS Location, ROUND(SUM(PurchaseAmount),2) AS Purchases, COUNT(PurchaseAmount) AS Visits
FROM web
GROUP BY UserID
UNION
SELECT UserID, "Store" AS Location, ROUND(SUM(PurchaseAmount),2) AS Purchases, COUNT(PurchaseAmount) AS Visits
FROM store
GROUP BY UserID
) AS summary
LEFT JOIN Newsletter ON summary.UserID = Newsletter.UserID
ORDER BY UserID;
CREATE TABLE salesdw_long AS
SELECT summary.UserID, Location, Purchases, Visits,
CASE
WHEN Newsletter.UserID IS NULL THEN 0
ELSE 1
END AS Newsletter
FROM
(
SELECT UserID, "Online" AS Location, ROUND(SUM(PurchaseAmount),2) AS Purchases, COUNT(PurchaseAmount) AS Visits
FROM web
GROUP BY UserID
UNION
SELECT UserID, "Store" AS Location, ROUND(SUM(PurchaseAmount),2) AS Purchases, COUNT(PurchaseAmount) AS Visits
FROM store
GROUP BY UserID
) AS summary
LEFT JOIN Newsletter ON summary.UserID = Newsletter.UserID
ORDER BY UserID;
--
SELECT Newsletter, Location,
SUM(Purchases) AS Purchases_Total, SUM(Visits) AS Visits, SUM(Purchases)/SUM(Visits) AS Visit_Avg
FROM salesdw_long
GROUP BY Newsletter, Location WITH ROLLUP;
SELECT Visits, COUNT(*) AS Freq
FROM salesdw_long
WHERE Location = "Online"
GROUP BY Visits WITH ROLLUP;
SELECT Location, Visits, COUNT(*) AS Freq
FROM salesdw_long
GROUP BY Location, Visits WITH ROLLUP;