[英]SQL SUM() function always returns 0
I'm executing this statement on an ASP.NET platform with SQL Server 我正在使用SQL Server在ASP.NET平台上执行此语句
SELECT id, size, color,
SUM(CASE WHEN storeID IN ('E13','E15','E10') THEN stock ELSE 0 END)
+ SUM(CASE WHEN storeID IN ('E13','E15','E10') THEN incoming ELSE 0 END)
- SUM(CASE WHEN storeID IN ('E13','E15','E10') THEN outgoing ELSE 0 END)
AS Total
FROM stocks
GROUP BY id, size, color
And this is the code I'm using to retrieve the obtained values 这是我用来检索获得的值的代码
For Each rowStock In TableStocks.Rows
Dim product As New ProductInfo
With product
.id = rowStock("id")
.size = rowStock("size")
.color = rowStock("color")
.stock = rowStock("Total")
End With
Next
id
, size
and color
values are correct, but the result of the SUM
function is always 0. If I run the query on the SQL Server management it works fine. id
, size
和color
值正确,但是SUM
函数的结果始终为0。如果我在SQL Server管理上运行查询,则可以正常工作。
I've tried changing 我尝试改变
.stock = rowStock(3)
instead of 代替
.stock = rowStock("Total")
but I'm getting the same result. 但我得到了相同的结果。 I can't figure what I'm missing. 我不知道我在想什么。
Finally I found a solution to my own question. 最后,我找到了解决自己问题的方法。 I've saved my query into a stored procedure on the database and it works as I expected. 我已经将查询保存到数据库的存储过程中,并且可以按预期工作。
EDIT 编辑
I've found another solution without using stored procedures. 我发现了另一个不使用存储过程的解决方案。 I realized that before running the sql statement, it's converted to lower case. 我意识到在运行sql语句之前,它已转换为小写形式。 So I decided to use COLLATE SQL_Latin1_General_CP1_CI_AS
in storeID
field, just to give it a try. 因此,我决定在storeID
字段中使用COLLATE SQL_Latin1_General_CP1_CI_AS
,只是尝试一下。 It worked! 有效!
The final SQL query is 最终的SQL查询是
SELECT id, size, color,
SUM(CASE WHEN storeID COLLATE SQL_Latin1_General_CP1_CI_AS
IN ('E13','E15','E10') THEN stock + incoming - outgoing ELSE 0 END)
AS Total
FROM stocks
GROUP BY id, size, color
The only thing I see is the extra comma after "total," which indicates another column name is expected in the query before the "from" keyword and choking... 我唯一看到的是“总计”之后的多余逗号,它表示查询中的另一个列名应在“ from”关键字之前并被阻塞...
Other than that, I would alter your query to ... 除此之外,我会将您的查询更改为...
SELECT
id, size, color, sum( stock + incoming - outgoing ) as Total
FROM
stocks
where
storeID IN ('E13','E15','E10')
GROUP BY
id, size, color
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.