简体   繁体   中英

SQL - Sum values in column by another column's value without grouping

I have a dataset that looks like this:

Location   Name    Amount
1          Bob     5        
1          Phil    1        
1          Bob     2        
West       Phil    2        
West       Phil    3        

I would like a column that will look at Location and Name, and sum all the data in Amount that has the same values without grouping. Location and name can all be wildly different. It would look like this:

Location   Name    Amount   Total
1          Bob     5        7
1          Phil    1        1
1          Bob     2        7
West       Phil    2        5
West       Phil    3        5

I'm pretty lost on what to do here. If this was in Excel it would be super easy with a SUMIFS! All help is appreciated!

You can use a scalar subquery to get that sum.

For example:

select *,
  (select sum(Amount) from my_table a 
   where a.Location = t.Location and a.Name = t.Name) as Total
from my_table t

Without grouping you can do it if your MySql version supports window functions:

select *, sum(amount) over (partition by location, name) total
from tablename

Without window functions you can do it with a subquery that returns the total:

select t.*, (select sum(amount) from tablename where location = t.location and name = t.name)) total
from tablename t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM