![](/img/trans.png)
[英]C#: How declare a variable to hold a sum and increment this variable each time through a while loop
[英]How to hold a SQL SUM() query int a Variable
美好的一天。 如圖所示,我在C#中有一個SQL查詢。
using (SQLiteConnection con = new SQLiteConnection(Connection.DatabaseLocationString))
{
SQLiteCommand cmd = null;
string query =
String.Format("SELECT MONTH(SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {0}
WHERE YEAR(SaleDate) = @1
GROUP BY MONTH(SaleDate) ", Sale.TABLE_NAME);
cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add(
new SQLiteParameter("@1", Properties.Settings.Default.ChartYearlyDisplay));
con.Open();
SQLiteDataReader reader = cmd.ExecuteReader();
con.Close();
}
我的挑戰是,我從未做過這樣的查詢。 但是我想要實現的是,我也SUM(AmountPaid)
這樣每月獲取SUM(AmountPaid)
的值。
但是我真的不知道那怎么回事。 請我需要您的幫助,謝謝。
您只需要使用SQLiteDataReader遍歷返回的結果
SQLiteDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader["month"].ToString());
Console.WriteLine(reader["sum_amountpaid"].ToString());
}
con.Close();
當然,如果需要返回此數據,則需要一個數據結構,可以在其中存儲結果,例如List<T>
// The class where you keep the value for a single month...
public class MonthAmount
{
public int Month {get;set;}
public decimal Amount {get;set;}
}
....
// A List where each month of data will be added...
List<MonthAmount> amountData = new List<MonthAmount>();
while(reader.Read())
{
// Create the instance of MonthAmount for the current month..
MonthAmount m = new MonthAmount()
{
Month = Convert.ToInt32(reader["month"]);
Amount = Convert.ToDecimal(reader["sum_amountpaid"]);
}
// Add it to the list...
amountData.Add(m);
}
reader.Close();
// Return the info to the caller....
return amountData;
同樣根據SQLite docs ,沒有MONTH或YEAR函數可用,您應該使用具有適當設置的strftime。 您可以嘗試
string query = $"SELECT strftime('%', SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {Sale.TABLE_NAME}
WHERE strftime('%Y', SaleDate) = @1
GROUP BY strftime('%m', SaleDate)";
而且,如果我沒記錯,那么此strftime函數的結果是一個字符串,而不是整數(IE為3月的“ 03”,年份為2017的字符串),因此也許您應該創建具有正確數據類型的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.