简体   繁体   中英

How to sum multiple columns and rows grouped by customer

I am trying to get a final column that adds up all the interest columns as one final number so that there is one number per customer. I currently have:

+--------+--------+-------+-------+-------+-------+
|Customer|Number  |IntMax |IntMin |IntMin1|IntMax1|
+--------+--------+-------+-------+-------+-------+
|Jones   |72352516|$0.00  |$381.47|$0.00  |$0.00  |
+--------+--------+-------+-------+-------+-------+
|Jones   |72352516|$455.31|$0.00  |$0.00  |$0.00  |
+--------+--------+-------+-------+-------+-------+
|Brett   |70920356|$0.00  |$0.00  |$194.56|$129.71|
+--------+--------+-------+-------+-------+-------+
|Gavin   |79023561|$0.00  |$617.29|$0.00  |$0.00  |
+--------+--------+-------+-------+-------+-------+
|Gavin   |79023561|$531.46|$0.00  |$0.00  |$0.00  |
+--------+--------+-------+-------+-------+-------+

What I want to see as a result is:

+--------+--------+---------+
|Customer|Number  |IntFinal |
+--------+--------+---------+
|Jones   |72352516|$836.78  |
+--------+--------+---------+
|Brett   |70920356|$324.27  |
+--------+--------+---------+
|Gavin   |79023561|$1,148.76|
+--------+--------+---------+

Thanks so much

SELECT Customer, Number, 
       SUM(IntMax + IntMin + IntMin1 + IntMax1) AS IntFinal
  FROM Table1
 GROUP BY Customer, Number

Output:

| CUSTOMER |   NUMBER | INTFINAL |
|----------|----------|----------|
|    Brett | 70920356 |   324.27 |
|    Jones | 72352516 |   836.78 |
|    Gavin | 79023561 |  1148.75 |

Here is SQLFiddle demo

<!-- language: lang-sql -->
  SELECT Customer,Number,SUM((IntMax+IntMin+IntMin1+IntMax1)) as IntFinal
    FROM tablename
GROUP BY Customer,Number
create table #temp
(
    Customer varchar(12) not null,
    Number  int not null,
    IntMax decimal(19,6),
    IntMin decimal(19,6),
    IntMin1 decimal(19,6),
    IntMax1 decimal(19,6),
)
insert into #temp values('Jones',72352516,'0.00','381.47','0.00','0.00')
insert into #temp values('Jones',72352516,'455.31','0.00','0.00','0.00')
insert into #temp values('Brett',70920356,'0.00','0.00','194.56','129.71')
insert into #temp values('Gavin',79023561,'0.00','617.29','0.00','0.00')
insert into #temp values('Gavin',79023561,'531.46','0.00','0.00','0.00')

select * from #temp

select t1.Customer, t1.Number, SUM(T1.IntMax+t1.IntMax1+t1.IntMin+t1.IntMin1) as    IntFinal from #temp t1 group by t1.Customer, t1.Number

drop table #temp

Thanks for all your answers guys - I ended up finding the below answer also:

SELECT Interest_Min_Max1.Customer, CCur(Sum([IntMax])+Sum([IntMin])+Sum([IntMax1])+Sum([IntMin1])) AS Total FROM Table 1 GROUP BY Interest_Min_Max1.Customer, Interest_Min_Max1.Number;

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