我是SQL的初学者,试图找出“Skillet”艺术家制作的CD的平均价格与数据库中所有CD的平均价格之间的差异
E.g。如果平底锅cds的平均值= 6英镑,所有cds的平均价格= 8英镑,那么就有2英镑的差距(绝对值)
这样的事情:
SELECT AVG(cdPrice) FROM cd
减去
SELECT AVG(cdPrice)
FROM cd, artist
WHERE artName = "Skillet" AND artist.artID = cd.artID
由于
答案 0 :(得分:3)
如果我正确理解你的问题,你会找到类似的东西:
SELECT AVG(cdPrice)-(SELECT AVG(cdPrice) FROM cd JOIN artist ON artist.artID = cd.artID WHERE artName = "Skillet") FROM cd;
答案 1 :(得分:1)
select x.avg_overall - y.avg_skillet as net_avg
from (select avg(cdprice) as avg_overall from cd) x
cross join (select avg(cdprice) as avg_skillet
from cd
join artist
using (artid)
where artname = 'Skillet') y
答案 2 :(得分:1)
试试这个,不需要子查询或交叉连接或其他任何东西。
select sum(case when a.name = 'skillet' then c.cdprice else 0 end) / sum(case when a.name = 'skillet' then 1 else 0 end) skillet_average,
avg(c.cdprice) cd_avg,
abs((sum(case when a.name = 'skillet' then c.cdprice else 0 end) / sum(case when a.name = 'skillet' then 1 else 0 end)) - avg(c.cdprice)) diff
from cds c
inner join artist a
on c.artist_id = a.id;
答案 3 :(得分:1)
假设每张CD只有一位艺术家,只需使用条件聚合:
SELECT AVG(cdPrice) - AVG(CASE WHEN artName = 'Skillet' THEN cdPrice END)
FROM cd LEFT JOIN
artist
ON artist.artID = cd.artID;
两个注释:
FROM
子句中使用逗号。始终使用明确的JOIN
/ ON
语法。