如何根据不同的键(不同的列)获取列的总和

How to get the sum of a column based on a distinct key (different column)

我想知道如何得到不同的乘积总和

我有table

Name Rating
 A     3
 A     3
 B     4
 C     3
 C     3

我想要的最终结果是 SUM(case when distinct table1.name then rating)/Count(case when distinct table1.name then rating) 最终答案 = (3+4+3)/3 = 10/3 = 3.33

提前致谢

SUM/COUNT <=> AVG 所以

SqlFiddleDemo

SELECT (SUM(Rating) * 1.0)/COUNT(*)  AS result
FROM (
  SELECT DISTINCT *
  FROM tab
  ) AS sub;

可以是:

SqlFiddleDemo2

SELECT AVG(Rating)  AS result
FROM (
  SELECT DISTINCT *
  FROM tab
  ) AS sub;

只是换个角度。

求每个名字的平均评分,然后求分组的平均评分。

查询

select avg(t.`avg`) as `avg` from
(
  select Name,
  avg(rating) as `avg`
  from your_table_name
  group by Name
)t;

SQL Fiddle