我试图将多行的值相加。例如:
我的输出是:
ID Value
---------
1 3
1 4
我希望看到的是:
ID Value
---------
1 7
这是我的代码:
SELECT
id CASE sum(cast(value as float))
WHEN 0 THEN [other_value]
else ISNULL([value] ,'')
end AS 'Value'
FROM table1
WHERE id = 1
GROUP BY id
我在网上看到了一些解决方案,例如我必须包含GROUP BY
才能避免此错误:
在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句
中
但是,仍然没有总和。
注意:
值为varchar
,因此,我需要cast
答案 0 :(得分:4)
您只需要group by
id列。
select id, sum(cast(value as numeric))
from tablename
group by id
编辑:
SELECT
id,
sum (
case when cast(value as numeric) = 0 THEN cast([other_value] as numeric)
else cast(ISNULL([value] ,0) as numeric)
) end
AS totalvalue
FROM table1
GROUP BY id
答案 1 :(得分:2)
您正在尝试对字符串求和(即使您将其转换) 只有当您的ISNULL变为0或某个数值
时,查询才有效SELECT
id, SUM(CASE WHEN CAST(value AS FLOAT) = 0
THEN CAST([other_value] AS FLOAT)
ELSE ISNULL([value], 0)
END) AS 'Value'
FROM table1
WHERE id = 1
GROUP BY id
答案 2 :(得分:1)
如果你要做的是获取的是[ID]的每个ID的总和,如果非零,否则[other_value] ...这就是你需要的:
select
id,
SUM(coalesce(nullif(cast([value] as float),0), cast([other_value] as float), 0)) [Value]
from table1
group by id