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

时间:2015-10-12 08:16:44

标签: mysql sql vertica

我想知道如何获得不同的产品总数

我有桌子

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

提前致谢

2 个答案:

答案 0 :(得分:0)

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;

答案 1 :(得分:0)

只是另一种观点。

查找每个名称的平均评分,然后是分组的平均值。

<强>查询

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

SQL Fiddle