[英]Aggregate sum of a field when another row with the same ID is selected in SQL
[英]Sum for same ID in every row SQL
我的桌子如下。
r_Id Marks
1 25
1 25
1 25
2 30
2 30
现在我想要一个查询,其中应计算每个r_id的标记总和,结果应为
r_Id MARKS Sum
1 25 75
1 25 75
1 25 75
2 30 60
2 30 60
我需要在Oracle中不使用PL / SQL来执行此操作。 请帮忙。 我尝试在GROUP BY中使用CUBE,ROLLUP,GROUPING SETS,但没有任何效果。
您要为此使用分析功能。 这些是使用over
子句的函数:
select r_id, Marks, sum(Marks) over (partition by r_id)
from t;
您可以执行以下操作:
select table1.*, sums.mark_sum
from table1
inner join (
select r_id, sum(marks) mark_sum
from table1
group by r_id ) sums
on sums.r_id = table1.r_id
在SQLFiddle上: http ://sqlfiddle.com/#!4/5a935/2
select r_id,s.marks,t.p from table s
left join
(select r_id,sum(marks)p from table
group by r_id)t
on s.r_id=t.r_id
order by t.p asc;
希望这个左联接查询能回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.