[英]How can i get the sum of a database table to a variable?
I have a database table named Deposit
and one of the column name in it is 30-12-2013
. 我有一个名为
Deposit
的数据库表,其中一个列名是30-12-2013
。 The column has two values such as 54,26. 该列有两个值,例如54,26。
i want to get the sum of that column column into a variable. 我想将该列列的总和变为变量。 I use the following code:
我使用以下代码:
con.Open();
SqlCeCommand cmd11 = con.CreateCommand();
cmd11.CommandText = "select sum(30-12-2013) from Deposit";
int result = ((int)cmd11.ExecuteScalar());
displaylabel.Text = result.ToString();
con.Close();
But, I am getting the value of variable 'result' as -3990. 但是,我得到变量'result'的值为-3990。
Whats wrong with my code.. Please help me.. Thanks in advance.. 我的代码有什么问题..请帮帮我..先谢谢..
(30-12-2013) * 2 (because you have two entries) = -1995 * 2 = -3990 (30-12-2013)* 2(因为你有两个条目)= -1995 * 2 = -3990
You have to use: 你必须使用:
SELECT sum([30-12-2013])
FROM dbo.Deposit
尝试为具有不寻常名称的列使用括号 -
cmd11.CommandText = "SELECT SUM([30-12-2013]) FROM Deposit";
This has already been answered so instead of answering your actual question I am going to propose an alternative solution. 这已经得到了回答,所以我没有回答你的实际问题,而是提出另一种解决方案。
Instead of having a table as follows: 而不是如下表:
SomeColumn | 30-12-2013 | 31-12-2013 | 01-01-2014
-----------+------------+------------+------------
A | 540 | 100 | 246
B | 130 | 90 | 377
Have a normalised table: 有一个规范化的表格:
SomeColumn | Date | Amount
-----------+------------+--------
A | 2013-12-30 | 540
A | 2013-12-31 | 100
A | 2014-01-01 | 246
B | 2013-12-30 | 130
B | 2013-12-31 | 90
B | 2014-01-01 | 377
This means you don't require a new column for every day. 这意味着您不需要每天都有新列。 So your query would become:
所以你的查询将成为:
SELECT SUM(Amount) AS Amount
FROM Deposit
WHERE Date = '20131230';
And if you wanted to reproduce your original structure you can use: 如果您想重现原始结构,可以使用:
SELECT SomeColumn,
SUM(CASE WHEN Date = '20131230' THEN Amount ELSE 0 END) AS [30-12-2013],
SUM(CASE WHEN Date = '20131231' THEN Amount ELSE 0 END) AS [31-12-2013],
SUM(CASE WHEN Date = '20140101' THEN Amount ELSE 0 END) AS [01-01-2014]
FROM Deposit
GROUP BY SomeColumn;
Example on SQL Fiddle (Using SQL Server as it doesn't support SQL Server CE) 关于SQL小提琴的示例 (使用SQL Server,因为它不支持SQL Server CE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.