SQL SUM函数没有分组数据

mpg*_*mpg 1 mysql sql aggregate-functions

我需要对由某些其他变量打破的变量求和.我通常会使用该group by功能执行此操作.

但是在这种情况下,我不想汇总数据.我想保留原始数据与某种聚合sum.

-ID-- --amount--
  1        23
  1        11
  1        8
  1        7
  2        10
  2        20
  2        15
  2        10
Run Code Online (Sandbox Code Playgroud)

结果

-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
Run Code Online (Sandbox Code Playgroud)

Tar*_*ryn 5

您可以使用子查询获取每个子查询的总数id并将其连接回您的表:

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;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo