加入2个包含计数的表格,包括不匹配的行

时间:2018-01-19 11:44:28

标签: sql sql-server

我有两张桌子,BANDSSONGS,我想列出录制少于3首歌曲的所有乐队,包括那些没有录制任何歌曲的乐队,以及一个点数歌曲的数量。

现在我有这个代码在歌曲数量旁边打印IDs。如何将IDs加入BANDS表并打印带名而不是IDs

另外如何展示没有录制任何歌曲的乐队?

    select ID as NAME, count(*) as NUMBER_OF_SONGS from SONGS
    group by ID
    having count(*) < 3;

2 个答案:

答案 0 :(得分:2)

您正在寻找left join

select b.name, count(s.bandid) as NUMBER_OF_SONGS
from bands b left join
     songs s
     on b.bandid = s.bandid  -- or whatever your join conditions are
group by b.name
having count(s.bandid) < 3;

答案 1 :(得分:2)

这里有一个完整的,希望更有用的答案,它说明了样本数据及其产生的结果。请运行以下示例:

CREATE TABLE #band
    (
        BandId INT ,
        BandName NVARCHAR(10)
    );

CREATE TABLE #song
    (
        SongId INT ,
        BandId INT ,
        SongName NVARCHAR(10)
    );

INSERT INTO #band ( BandId ,
                    BandName )
VALUES ( 1, 'Rockers' ) ,
       ( 2, 'Rappers' ) ,
       ( 3, 'Ravers' ) ,
       ( 4, 'Poppers' );

INSERT INTO #song ( SongId ,
                    BandId ,
                    SongName )
VALUES ( 1, 1, 'rock 1' ) ,
       ( 2, 1, 'rock 2' ) ,
       ( 3, 1, 'rock 3' ) , -- rock = 3 songs - not output
       ( 4, 2, 'rap 1' ) , 
       ( 5, 2, 'rap 2' ) ,  -- rap = 2 songs - is output
       ( 6, 3, 'rave 1' );  -- rave = 1 song - is output
        -- pop = 0 songs - is output

SELECT   b.BandId ,
         b.BandName ,
         COUNT(s.SongId) Songs
FROM     #band AS b
         LEFT JOIN #song AS s ON s.BandId = b.BandId  -- left join includes 0's
GROUP BY b.BandId ,
         b.BandName
HAVING   COUNT(s.SongId) < 3;  -- filters to bands with less than 3 songs

DROP TABLE #band;
DROP TABLE #song;

产地:

BandId      BandName   Songs
----------- ---------- -----------
4           Poppers    0
2           Rappers    2
3           Ravers     1