我在SQL中使用group by和aggregate函数比较新,我有以下表格:
CREATE TABLE `artists` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR( 100 ) NOT NULL );
CREATE TABLE `genres` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR( 100 ) NOT NULL);
CREATE TABLE `songs` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR( 100 ) NOT NULL, `artist_id` INT NOT NULL );
CREATE TABLE `songs_genres` (`song_id` INT NOT NULL, `genre_id` INT NOT NULL );
我希望找回有多种类型歌曲的艺术家。欢迎任何想法!
到目前为止,我已将此链接到一起,但无法完成所需的分组/聚合:
select a.name as name, g.name as genre
from artists a inner join songs s on a.id = s.artist_id
inner join songs_genres sg on s.id = sg.song_id
inner join genres g on g.id = sg.genre_id
提前致谢。
答案 0 :(得分:0)
这可能会有所帮助。它会发现有多少类型有多个艺术家:
SELECT COUNT(a.Name) AS "No. of Artists",
g.Name AS "Genre"
FROM Artists a
INNER JOIN songs s on a.id = s.artist_id
INNER JOIN songs_genres sg on s.id = sg.song_id
INNER JOIN genres g on g.id= sg.genre_id
GROUP BY g.Name
这将为您提供每位艺术家的流派数量:
SELECT COUNT(g.Name) AS "No. of Genres",
a.Name AS "Artist"
FROM Artists a
INNER JOIN songs s on a.id = s.artist_id
INNER JOIN songs_genres sg on s.id = sg.song_id
INNER JOIN genres g on g.id= sg.genre_id
GROUP BY a.Name
添加HAVING
条款可让您将结果范围缩小到超过任意数量的艺术家/流派:
SELECT COUNT(g.Name) AS "No. of Genres",
a.Name AS "Artist"
FROM Artists a
INNER JOIN songs s on a.id = s.artist_id
INNER JOIN songs_genres sg on s.id = sg.song_id
INNER JOIN genres g on g.id= sg.genre_id
GROUP BY a.Name
HAVING Count(g.Name) > 1 -- or 2, or 10. This will skip over single-genre artists
您在这些查询中所做的是计算在按其他值分组时给定值显示的次数。
答案 1 :(得分:0)
您可以按文档http://www.w3schools.com/sql/sql_groupby.asp查看分组,我认为您可以执行以下操作
select a.name as name, g.name as genre
from artists a inner join songs s on a.id = s.artist_id
inner join songs_genres sg on s.id = sg.song_id
inner join genres g on g.id = sg.genre_id
group by name, genre desc
我希望这会有所帮助,您也可以查看此威胁Using group by on multiple columns