C# 如何在变量中保存SQL SUM()查询
你好。 我在C#中有一个SQL查询,如图所示C# 如何在变量中保存SQL SUM()查询,c#,sql,sqlite,C#,Sql,Sqlite,你好。 我在C#中有一个SQL查询,如图所示 using (SQLiteConnection con = new SQLiteConnection(Connection.DatabaseLocationString)) { SQLiteCommand cmd = null; string query = String.Format("SELECT MONTH(SaleDate) month,
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)
值,如下所示
- 一月=20000.00
- 二月=18000.00
- 三月=10000.00 ……等等
我需要您的帮助,谢谢。您只需要使用SQLiteDataReader循环返回的结果
SQLiteDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader["month"].ToString());
Console.WriteLine(reader["sum_amountpaid"].ToString());
}
con.Close();
当然,如果需要返回此数据,则需要一个数据结构,在该结构中可以像存储列表那样存储结果
如果我没有错的话,这个strftime函数的结果是一个字符串而不是一个整数(例如,2017年3月为'03',2017年3月为'03',因此也许您应该创建一个具有正确数据类型的参数。我删除了不兼容的数据库标记。请只标记您实际使用的数据库。但问题是什么?你试过那个问题吗?或者您只是想知道如何读取返回的值?关于如何使用SQLiteDataReader
的任何示例都将包括如何读取其中的值。你试过什么,什么不起作用?你是在找如何用C#从数据库中读取数据的教程吗?我读得很好,重新读了我的问题,我说我需要帮助阅读一年中每个月的数据。@Steve,是的。。。。我只是想知道如何读取返回的值。好的,非常感谢@Steve,非常感谢。但是它抛出了一个错误没有这样的函数:MONTH
。我如何使用SQLite.Uhm进行查询,这意味着SQLite上没有月函数。我正在查找,您似乎需要strftime(“%m”,SaleDate)而不是月份
// 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;
string query = $"SELECT strftime('%', SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {Sale.TABLE_NAME}
WHERE strftime('%Y', SaleDate) = @1
GROUP BY strftime('%m', SaleDate)";