如何在mssql中做列的总和

时间:2016-07-28 08:44:16

标签: sql sql-server sql-server-2008

我写了以下查询来获取名称和金额:

  select fm.familyname,qt.amount
  from Registrations rs left join Family fm on fm.id = rs.family_id
  left join Quote qt on qt.id = rs.quote_id
  group by  fm.familyname,qt.amount

所以从上面的查询我得到以下答案:

name    amount
abc     1200
abc     1300
abc     1400

但我希望输出如下:

name    amount
 abc    3900

我该怎么做?我使用了Sum(isnull(cast(qt.amount as float),0)) as total,但它正在完成单个列。

我怎样才能获得总数?

2 个答案:

答案 0 :(得分:3)

单独GROUP BY fm.familyname

select fm.familyname, SUM(qt.amount)
from Registrations rs
  left join Family fm on fm.id = rs.family_id
  left join Quote qt on qt.id = rs.quote_id
group by  fm.familyname 

如果你得到“操作数数据类型varchar(max)对sum运算符无效。”,你需要cast该列,如:

select fm.familyname, sum(cast(qt.amount as float))
...

答案 1 :(得分:1)

select fm.familyname,
SUM(
    CASE ISNUMeric(LTRIM(RTRIM(ISNULL(qt.amount,'0')))) WHEN 1 THEN CAST(qt.amount as decimal(10,2)) ELSE 0 END
) AS amount
from Registrations rs left join Family fm on fm.id = rs.family_id
left join Quote qt on qt.id = rs.quote_id
group by  fm.familyname