Forum

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;

 

Answers

Hi Sylvia,

Your code looks good, there is nothing wrong with it.

I slightly prefer the official solution as it's easier for me to understand.

Logically, the (official solution)'s first step is to aggregate the artist's streamings by country using artist_id, then from artist_id look for their meta data (id, name).

This is such a simple question, so breaking down the problems into multiple parts may not seem to be super helpful, but for any complicated interview questions, I'd suggest breaking down it into multiple parts, so it's easy for the interviewer to understand and for you to debug if needed.

Cheers,

Leon

SQLPad user avatar

Leon (949)

April 19, 2022, 11:14 a.m.