I have a database table named Deposit
and one of the column name in it is 30-12-2013
. The column has two values such as 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.
Whats wrong with my code.. Please help me.. Thanks in advance..
(30-12-2013) * 2 (because you have two entries) = -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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.