Posted by Sylvia, April 18, 2022, 10:53 p.m.
Question# 89 Top 5 Artists
Just out of curiosity -
- With the "WHERE c.country = 'US'" clause limiting the total number of song plays to be in the US, my answer essentially arrives at the same result as the solution. Is there any reason for preference that I may have overlooked?
My answer:
WITH song_play AS (
SELECT a.artist_id,
MAX(a.name) as name,
SUM(c.num_plays) AS num_plays
FROM artist a
INNER JOIN song b
ON a.artist_id = b.artist_id
INNER JOIN song_plays c
ON b.song_id = c.song_id
WHERE c.country = 'US' AND DATE(c.date) = '2021-01-01'
GROUP BY a.artist_id
)
SELECT artist_id, name
FROM song_play
ORDER BY num_plays
LIMIT 5
Solution:
WITH artist_plays AS (
SELECT
S.artist_id,
P.country,
SUM(num_plays) num_plays
FROM song_plays P
INNER JOIN song S
ON S.song_id = P.song_id
WHERE P.date = '2021-01-01'
AND P.country = 'US'
GROUP BY 1,2
)
SELECT A.artist_id, A.name
FROM artist_plays P
INNER JOIN artist A
ON A.artist_id = P.artist_id
ORDER BY num_plays DESC
LIMIT 5;