求和sql行并添加到新列

时间:2014-02-15 06:16:49

标签: sql

说我对此查询有这个结果..

customername      p8    p12   p750   p1   m8
customer1         5     48     4     4    4
customer2         4            2     5    43
customer3         4     -3     

现在我想问一下是否有办法可以添加所有行来形成这样的东西:

customername      p8    p12   p750   p1   m8     total
customer1         5     48     4     4    4       65
customer2         4            2     5    43      54
customer3         4     -3                        1

任何人都可以帮我这个吗?

3 个答案:

答案 0 :(得分:3)

create table tbl1 (m1 int, m2 int);

insert into tbl1 (m1,m2) values 
(25,50),(30,43);

<强>查询:

select m1,m2, (m1+m2) as total from tbl1;

Demo

答案 1 :(得分:3)

汇总字段并使用别名命名选择

中的动态列
select coalesce(p8,0)+
       coalesce(p12,0)+
       coalesce(p750,0)+
       coalesce(p1,0)+
       coalesce(m8,0) as total
from your_table

如果您的某些专栏允许null,那么您必须使用coalesce之类的功能将0替换为1+null=null

答案 2 :(得分:1)

SELECT customername,   p8, p12 , p750, p1, m8, 
 COALESCE (p8,0) + COALESCE (p12,0) + COALESCE (p750,0) +     COALESCE (p1,0) + COALESCE (m8,0) AS total
FROM table