sql 多列字段同时求和

来源:百度知道 编辑:UC知道 时间:2024/05/30 10:09:16
字段1 字段2 字段3 字段4 字段5 字段6
1 1 1 1 2 3

1 1 1 2 3 4

2 2 2 1 2 3
2 2 2 2 3 4

求和得到结果是
字段1 字段2 字段3 字段4 字段5 字段6
1 1 1 3 5 7
2 2 2 3 5 7

请问sql语句如何写?

这是标准的分组查询,用group by 就可以了:
select 字段1,字段2,字段3, sum(字段4),sum(字段5),sum(字段6) from 表 group by 字段1,字段2,字段3

看你下一百分,再告诉你个知识点:
表table
name course source
张三 语文 90
张三 数学 80
李四 语文 80
李四 数学 75

要得到结果:
name chinese math average
张三 90 80 85
李四 80 75 77.5

利用case when 分类查询语句为:
select name,max(case course when '语文' then source else 0 end)as chinese,
max(case course when '数学' then source else 0 end)as math,
avg(source) as average
from table group by name

测试通过
希望你能掌握这两个常用关键字

创建测试表
CREATE TABLE [test] (
[a] [int] NULL ,
[b] [int] NULL ,
[c] [int] NULL ,
[d] [int] NULL ,
[e] [int] NULL ,
[f] [int] NULL
) ON [PRIMARY]
GO

查询程序
select a,b,c,sum(d),sum(e),sum(f) from test
group by a,b,c

结果
1 1 1 3 5 7
2 2 2 3 5 7