如何通过分组依据求和?

时间:2019-03-18 17:20:32

标签: sql postgresql

我有一张桌子,像这样:

ID   Marks  Weightatthistime
1    5          44  
1    5          43 
1    5          41  
2    4          39
2    4          38

我希望这些ID获得的总分数,所以我希望查询返回:9。 我知道我可以做到:

select ID, sum(Marks) from table group by 1

但是我只是想要总和而不是另一个迷你表。该表是在此级别汇总的,我无法对其进行更改。

4 个答案:

答案 0 :(得分:1)

使用子查询:

select id, sum(marks)
from (select distinct id, marks
      from table t
     ) t
group by id;

如果只想使用sum,请只使用sum(marks)

select sum(marks)
from (select distinct id, marks
      from table t
      ) t;

答案 1 :(得分:0)

使用不同的

   select sum( distinct Marks) from table




  with cte as
(
select 1 id, 5 as m union all
select 1,5 union all
select 1,5 union all
select 2,4 union all
select 2,4
) select sum(distinct m) from cte

但是如果多个用户具有相同的号码,则遵循显示@Yogesh的子查询方法

输出

9

答案 2 :(得分:0)

我相信这适用于任何ANSI SQL引擎。

Select ID, Marks, Weightatthistime, (Select Sum(Marks) From Table1) SumAllMarks
   From Table1 

这将在每条记录上放置9。

答案 3 :(得分:0)

  

从表中选择总和(DISTINCT标记);

您可以使用此查询获取不同标记值的总和。

相关问题