SQL 不同值之和的内连接

SQL INNER JOIN of sum distinct values

我有 3 个表,分别是 musicssingersplaylistInfos。 我想获得前 10 个收听的英格兰 musics.What 类型的 sql 查询帮助我?

musics
musicID | singerID
1         1
2         1
3         2

singers
singerID | name |  country
1          Adele   England
2          Mozart  Austria
3          DuaLipa England

playlistInfo
id | singerID | musicID | listened
1    1          1         25
2    3          3         15
3    2           2         20

SELECT * FROM musics m INNER JOIN playlistInfo p ON p.musicID = m.id INNER JOIN singer a ON a.id = m.singerID GROUP BY p.musicID ORDER BY p.listened

我尝试了这个,但我没有得到原来的结果expecting.How我可以修复它吗?

嗯,首先你的样本数据是错误的。所以首先让我们创建正确的结构。

请记住,如果您将来共享 sql 脚本来创建示例数据,您将获得更多答案。

-- declare tables
DECLARE @singers TABLE (singerID INT, name NVARCHAR(255), country NVARCHAR(255));
DECLARE @musics TABLE (musicID INT, singerID INT, songName NVARCHAR(255));
DECLARE @playlistInfo TABLE (singerID INT, musicID INT, listened INT);

-- Load sample data
INSERT INTO @singers VALUES (1, 'Adele', 'England'), (2, 'Mozart', 'Austria'), (3, 'DuaLipa', 'England')
INSERT INTO @musics VALUES (1, 1, 'Rolling in the Deep'), (2, 2, 'Symphony No 40'), (3, 3, 'One Kiss')
INSERT INTO @playlistInfo VALUES (1, 1, 25), (2, 2, 15), (3, 3, 20)

然后在我们的表格中查询来自英国的前 10 位歌手。

SELECT TOP 10
    s.name as Singer, ISNULL(SUM(pl.listened), 0) as TotalListened
FROM 
    @singers s
    LEFT JOIN @musics m ON m.singerID = s.singerID
    LEFT JOIN @playlistInfo pl ON pl.musicID = m.musicID AND pl.singerID = m.singerID
    -- I did left join to show anyone with 0 listen too, you can convert it to `JOIN`
WHERE
    s.country = 'England'
GROUP BY
    s.name
ORDER BY
    SUM(pl.listened) DESC

一些额外的东西(如果你想获得最多听的歌曲)

-- get the most listened song within country
SELECT TOP 10
    s.name as Singer, m.songName, ISNULL(SUM(pl.listened), 0) as TotalListened
FROM 
    @singers s
    LEFT JOIN @musics m ON m.singerID = s.singerID
    LEFT JOIN @playlistInfo pl ON pl.musicID = m.musicID AND pl.singerID = m.singerID
WHERE
    s.country = 'England'
GROUP BY
    s.name,
    m.songName
ORDER BY
    SUM(pl.listened) DESC