我正在尝试编写一个子查询来加入“专辑”和“曲目”表。
最终我需要弄清楚专辑中平均有多少首歌曲名称中带有“摇滚”一词。所选专辑必须至少包含八首歌曲。
SELECT AVG(tr.track_id)
FROM(SELECT al.album_id AS album,
tr.name,
COUNT(tr.track_id)
FROM track as tr
LEFT OUTER JOIN album as al ON al.album_id = tr.album_id
WHERE tr.name LIKE '%Rock%'
GROUP tr.name )AS ag
HAVING COUNT(al.album_id) >= 8;
你很接近。
HAVING
子句应该在内部查询中,仅过滤其中包含超过 8 首歌曲的歌曲。你也按曲目名称而不是专辑名称过滤,所以我也改变了它。
SELECT AVG(ag.cnt)
FROM(SELECT al.album_id AS id,
COUNT(*) as cnt
FROM track as tr
JOIN album as al ON al.album_id = tr.album_id
WHERE al.name LIKE '%Rock%'
GROUP al.album_id
HAVING COUNT(al.album_id) >= 8 ) AS ag
SELECT AVG(ag.count_track)
FROM (
SELECT
a.title,
COUNT(t.track_id) as count_track
FROM track AS t
LEFT OUTER JOIN album AS a ON a.album_id = t.album_id
WHERE a.title LIKE '%Rock%'
GROUP BY a.title
) AS ag
WHERE count_track >= 8