0

Select all songs together with the number of playlists they are member of.

Select 
    Title, Count(*) as 'number of playlists they are member of' 
from 
    Song 
inner join 
    PlaylistSong on PlaylistSong.songID = Song.ID
inner join 
    Playlist on Playlist.ID = playlistsong.PlayListID
group by 
    Song.title

This solution almost works, but it doesn't show songs that are not assigned to any playlist. Are there any way to include those songs?

Please let me know if you need more information.

2
  • Be aware that string literals as column aliases is on the deprecation list (e.g. COUNT(*) AS 'alias'), and is already not supported in Azure. Use <expression> AS [Alias] or [Alias] = <expression> to avoid compatibility problems with future versions of SQL Server. A good article on this is Bad Habits to Kick : Using AS instead of = for column aliases Commented Nov 19, 2014 at 10:10
  • @GarethD Thanks, I'll have a look at that. Commented Nov 19, 2014 at 10:30

1 Answer 1

2

Use a left join instead

Select Song.Title, 
       Count(distinct Playlist.ID) as 'number of playlists they are member of' 
from Song 
left join PlaylistSong on PlaylistSong.songID = Song.ID 
left join Playlist on Playlist.ID = playlistsong.PlayListID 
group by Song.title
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the fast answer, but this still does not show songs that aren't on any playlist.
Should to be a left join to Playlist too, although this join is not actually required at all, could just join to playlist song and use COUNT(DISTINCT playlistsong.PlayListID)
Yes, I just tried using left join on both, and it worked. Thanks.
@Christopher, Since this answer helped you should consider choosing it as the accepted answer, this shows others that it helped, and will also remove the question from the unanswered pile.
@GarethD Think I did it now, thanks. This is the first time I've created a thread :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.