在SQL Server中使用COUNT不会显示空值

时间:2014-11-19 09:52:54

标签: sql-server

选择所有歌曲及其所属的播放列表数量。

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

此解决方案几乎可以使用,但它不会显示未分配给任何播放列表的歌曲。 有没有办法包括那些歌?

如果您需要更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:2)

使用left join代替

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