sql server 2010中连续列的总和

时间:2013-12-16 09:29:35

标签: sql-server-2008

我在sql:

中的表Mat中有以下类型的数据
Mid    Mat1    Mat2  Mat3   Mat4   Mat5
100     4        5    0     n/a     10
100     1        2    0     3       n/a
100     2        1    n/a   n/a     11
101     2        5    0     n/a     n/a
101     6        20   0     10      n/a

现在每个中间,我们需要将所有垫子相加,不包括n / a值。

我应该得到以下数据:

Mid     Mat1      Mat2      Mat3     Mat4    Mat5
100      7         8         0         3      21
101      8         25        0         10     0

有人可以建议如何在sql查询中实现这个???

2 个答案:

答案 0 :(得分:0)

试试这个

select  SUM(cast(Mat1    as int)) as mat1,SUM(cast(Mat2    as int)) as mat2,SUM(cast(Mat3    as int)) as mat3,SUM(cast(Mat4    as int)) as mat4,SUM(cast(Mat4    as int)) as mat4,SUM(cast(Mat5    as int)) as mat5 from Mat group by Mid    

答案 1 :(得分:0)

这应该有效

SELECT    
Mid,
  SUM(CAST(case when Mat1='n/a' then null Mat1 else  AS INT)) AS mat1,
  SUM(CAST(case when Mat2='n/a' then null Mat2 else  AS INT)) AS mat2,
  SUM(CAST(case when Mat3='n/a' then null Mat3 else  AS INT)) AS mat3,
  SUM(CAST(case when Mat4='n/a' then null Mat4 else  AS INT)) AS mat4,
  SUM(CAST(case when Mat4='n/a' then null Mat4 else  AS INT)) AS mat4,
  SUM(CAST(case when Mat5='n/a' then null Mat5 else  AS INT)) AS mat5
FROM Mat
GROUP BY Mid