-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathsolution.sql
67 lines (60 loc) · 2.03 KB
/
solution.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
-- ============================================
-- Challenge 1 - Who Have Published What At Where?
-- Get author details, title, and publisher name
-- ============================================
SELECT
a.au_id AS "AUTHOR ID",
a.au_lname AS "LAST NAME",
a.au_fname AS "FIRST NAME",
t.title AS "TITLE",
p.pub_name AS "PUBLISHER"
FROM titleauthor ta
JOIN authors a ON ta.au_id = a.au_id
JOIN titles t ON ta.title_id = t.title_id
JOIN publishers p ON t.pub_id = p.pub_id
ORDER BY a.au_id;
-- ============================================
-- Challenge 2 - Who Have Published How Many At Where?
-- Count number of titles per author at each publisher
-- ============================================
SELECT
a.au_id AS "AUTHOR ID",
a.au_lname AS "LAST NAME",
a.au_fname AS "FIRST NAME",
p.pub_name AS "PUBLISHER",
COUNT(*) AS "TITLE COUNT"
FROM titleauthor ta
JOIN authors a ON ta.au_id = a.au_id
JOIN titles t ON ta.title_id = t.title_id
JOIN publishers p ON t.pub_id = p.pub_id
GROUP BY a.au_id, p.pub_name
ORDER BY COUNT(*) DESC, a.au_lname, a.au_fname;
-- ============================================
-- Challenge 3 - Best Selling Authors
-- Top 3 authors by number of titles sold
-- ============================================
SELECT
a.au_id AS "AUTHOR ID",
a.au_lname AS "LAST NAME",
a.au_fname AS "FIRST NAME",
SUM(s.qty) AS "TOTAL"
FROM titleauthor ta
JOIN authors a ON ta.au_id = a.au_id
JOIN sales s ON ta.title_id = s.title_id
GROUP BY a.au_id
ORDER BY TOTAL DESC
LIMIT 3;
-- ============================================
-- Challenge 4 - Best Selling Authors Ranking
-- All authors ranked by sales (including zero)
-- ============================================
SELECT
a.au_id AS "AUTHOR ID",
a.au_lname AS "LAST NAME",
a.au_fname AS "FIRST NAME",
IFNULL(SUM(s.qty), 0) AS "TOTAL"
FROM authors a
LEFT JOIN titleauthor ta ON a.au_id = ta.au_id
LEFT JOIN sales s ON ta.title_id = s.title_id
GROUP BY a.au_id
ORDER BY TOTAL DESC;