user209396
user209396

Reputation: 59

Aggregate sum over a particular ID value in SQL Server

Say, I have 3 columns in my table :

---------------
name                 | ID  | Amt
ABC                  |  1  | 500
ABC                  |  1  | 650
XYZ                  |  2  | 700
XYZ                  |  2  | 550
DEF                  |  3  | 200

how can I get an output where the amount is aggregated for each ID, i.e., ABC gives 1150, XYZ 1250 and DEF 200?

Upvotes: 0

Views: 711

Answers (3)

FutbolFan
FutbolFan

Reputation: 13723

This could be done using a simple group by statement:

select name,
       id,
       sum(amt) as agg_sum
from total
group by name,id;

SQL Fiddle Demo

Upvotes: 0

Sam CD
Sam CD

Reputation: 2097

SELECT name,SUM(Amt) FROM [table] GROUP BY name

or, if you want to display name and ID

SELECT name,ID,SUM(Amt) OVER (PARTITION BY name) FROM [table]

Upvotes: 0

APH
APH

Reputation: 4154

You want a group by, with what sounds like a sum from your example:

Select Name, ID, sum(amt) as TotalAmt
from MyTable
Group by Name, ID

Upvotes: 1

Related Questions