Good day. I have an SQL query in C# as shown.
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();
}
My challenge is, i have never done nor used a query like this. But what i want to achieve is, i want too Get the value of SUM(AmountPaid)
for each month, like this.
But i really dont know how too come of that. please i need your help, Thanks.
You just need to loop over the returned results using the SQLiteDataReader
SQLiteDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader["month"].ToString());
Console.WriteLine(reader["sum_amountpaid"].ToString());
}
con.Close();
Of course, if you need to return this data, you need a data structure where you can store the results like a 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;
Also according to SQLite docs , there is no MONTH or YEAR functions available, you should use strftime with an appropriate settings. You could try with
string query = $"SELECT strftime('%', SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {Sale.TABLE_NAME}
WHERE strftime('%Y', SaleDate) = @1
GROUP BY strftime('%m', SaleDate)";
And if I am not wrong, the result of this strftime function is a string not an integer (IE '03' for March, '2017' for year) so perhaps you should create a parameter with the correct datatype.
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.