SQL SUM function without grouping data

£可爱£侵袭症+ 提交于 2019-12-14 02:47:40

问题


I need to do a sum of a variable broken by certain other variables. I normally would do this with the group by function.

However in this case, I do not want to roll-up the data. I want to keep the original data with some sort of aggregated sum.

-ID-- --amount--
  1        23
  1        11
  1        8
  1        7
  2        10
  2        20
  2        15
  2        10

Result

-ID-- --amount-----SUM
  1        23      49
  1        11      49
  1        8       49
  1        7       49
  2        10      55
  2        20      55
  2        15      55
  2        10      55

回答1:


You could use a subquery to get the total for each id and join that back to your table:

select t.id, 
  t.amount, 
  t1.total
from yt t
inner join 
(
  select id, sum(amount) total
  from yt
  group by id
) t1
  on t.id = t1.id;

See SQL Fiddle with Demo



来源:https://stackoverflow.com/questions/16846605/sql-sum-function-without-grouping-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!