简体   繁体   English

SQL分组平均值

[英]SQL grouping averages

在此处输入图片说明

Hi! 嗨! I'm new to SQL I'm having trouble correctly using the avg and sum function. 我是SQL的新手,无法正常使用avg和sum函数。 I'm working with the database above. 我正在使用上面的数据库。 I need to find the average profit for each movie star but only output that average only if the sum of their profits is > 200. 我需要找到每个电影明星的平均利润,但是只有当他们的利润总和> 200时才输出该平均利润。

 SELECT MovieStar.sname, avg(profit) From MovieStar, Movie
 GROUP BY sname
 HAVING sum(Movie.profit) > 200

I'm using SQL Fiddle to try and figure this out, but it seems to be returning the avg of the WHOLE profit column and not each actor but I'm not sure what I could be doing wrong. 我正在使用SQL Fiddle尝试解决此问题,但它似乎返回的是WHOLE Profit列的平均值,而不是每个参与者的平均值,但是我不确定自己可能做错了什么。 How can I approach this so I can get the avg of each actor and not the avg of the whole profit column? 我该如何解决这个问题,以便获得每个演员的平均值而不是整个利润栏的平均值? Here is the SQL Fiddle I made. 是我制作的SQL Fiddle。 Thanks in advance! 提前致谢!

Looks like the query is doing a CROSS JOIN operation, a cartesian product, matching every movie to each moviestar. 看起来查询正在执行CROSS JOIN操作,一种笛卡尔乘积,将每个电影与每个moviestar匹配。 Seems like we would only want to match a moviestar to particular movies, probably using (including) the starsin table to get the matches. 似乎我们只想将电影明星与特定电影匹配,可能使用(包括) starsin表来获取匹配项。

I recommend you ditch the old-school comma operator the join operation. 我建议您放弃老式逗号运算符的join操作。 Use the newer JOIN keyword instead. 改用较新的JOIN关键字。 And put the join predicates in the appropriate ON clause instead of the WHERE clause. 并将连接谓词放在适当的ON子句中,而不是WHERE子句中。

Also, best practice is to qualify all column references; 同样,最佳实践是限定所有列引用; even when not required to eliminate ambiguity, it prevents the query from breaking when new columns are added, and it aids the future reader... the poor soul who has to go look at the table definitions to figure out which columms come from which tables. 即使不需要消除歧义,它也可以防止在添加新列时查询中断,并且有助于将来的读者……不得不去查看表定义以找出哪些列来自哪些表的可怜的灵魂。

I think you want something like this: 我想你想要这样的东西:

 SELECT ms.sname
 --   , ms.sno
      , AVG(m.profit)  AS  avg_profit
 --   , SUM(m.profit)  AS  tot_profit 
   FROM MovieStar ms
   JOIN StarsIn si 
      ON si.sno = ms.sno
    JOIN Movie m
      ON m.mno = si.mno
   GROUP BY ms.sno, ms.sname
  HAVING SUM(m.profit) > 200
   ORDER BY AVG(m.profit) DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM