如何对按客户分组的多列和多行求和
Posted
技术标签:
【中文标题】如何对按客户分组的多列和多行求和【英文标题】:How to sum multiple columns and rows grouped by customer 【发布时间】:2014-01-21 02:20:01 【问题描述】:我正在尝试获得一个最终列,它将所有兴趣列加起来作为一个最终数字,这样每个客户就有一个数字。我目前有:
+--------+--------+-------+-------+-------+-------+
|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 |
+--------+--------+-------+-------+-------+-------+
我想看到的结果是:
+--------+--------+---------+
|Customer|Number |IntFinal |
+--------+--------+---------+
|Jones |72352516|$836.78 |
+--------+--------+---------+
|Brett |70920356|$324.27 |
+--------+--------+---------+
|Gavin |79023561|$1,148.76|
+--------+--------+---------+
非常感谢
【问题讨论】:
【参考方案1】:SELECT Customer, Number,
SUM(IntMax + IntMin + IntMin1 + IntMax1) AS IntFinal
FROM Table1
GROUP BY Customer, Number
输出:
|客户 |号码 |国际 | |---------|----------|----------| |布雷特 | 70920356 | 324.27 | |琼斯 | 72352516 | 836.78 | |加文 | 79023561 | 1148.75 |这里是SQLFiddle演示
【讨论】:
【参考方案2】: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
【讨论】:
【参考方案3】:<!-- language: lang-sql -->
SELECT Customer,Number,SUM((IntMax+IntMin+IntMin1+IntMax1)) as IntFinal
FROM tablename
GROUP BY Customer,Number
【讨论】:
【参考方案4】:感谢您的所有回答,我最终也找到了以下答案:
SELECT Interest_Min_Max1.Customer, CCur(Sum([IntMax])+Sum([IntMin])+Sum([IntMax1])+Sum([IntMin1])) AS Total 从表 1 GROUP BY Interest_Min_Max1.Customer, Interest_Min_Max1.Number;
【讨论】:
以上是关于如何对按客户分组的多列和多行求和的主要内容,如果未能解决你的问题,请参考以下文章