How to sum sqlite data rows

Hello guys. What I want to ask is how can i sum the row values in sqlite database then print it on a form label? I used the List<>QueryAsync() function and tried to print the return value on a label but it's showing me some string and list values

Answers

  • some1some1 Member ✭✭✭
    edited August 9

    @ous

    var incomeTab =await _connection.Table

    ().ToListAsync(); <List> cart = new List<Table>(incomeTab); cart.Sum(a => a.FieldName); `
  • JarvanJarvan Member, Xamarin Team Xamurai

    To get the sum of the data in the database, you should use SUM when querying.

    var sum = await database.ExecuteScalarAsync<int>("SELECT SUM(value_property) FROM table_name");
    

    Similar issue:
    https://stackoverflow.com/questions/52419378/xamarin-sqlite-query-with-sum
    https://forums.xamarin.com/discussion/150829/getting-whole-field-data-as-a-sum

  • ousous Member ✭✭

    jarvan I did something similar its asking for another argument. This is my code
    public Task SumItemAsync()
    {
    return db.ExecuteScalarAsync("SELECT SUM(Amount) FROM Spent",);

        }
    
  • ousous Member ✭✭
    It's in a sqlite helper class where I defined all the crud functions. So o also defined a sum function for this functionality but it's giving me a tough time since am a newbie in xamarin.
  • JarvanJarvan Member, Xamarin Team Xamurai

    Try to use the code in async method.

    public async Task SumItemAsync()
    {
        var data = await db.ExecuteScalarAsync("SELECT SUM(Amount) FROM Spent");
        return data;
    }
    
  • ousous Member ✭✭

    Jarvan I tried what you just gave me but it give me an error saying " the type arguments for method sqliteAsyncConnection.ExecuteScalarAsync(string, param object[]) cannot be infered from the usage. Try specifying the type argument explicitly" Any clue about this?

  • ousous Member ✭✭

    So when I opened the sqliteAsyncConnection, this is what I found about the ExecuteScalar:
    // Summary:
    // Creates a SQLiteCommand given the command text (SQL) with arguments. Place a
    // '?' in the command text for each of the arguments and then executes that command.
    // Use this method when return primitive values. You can set the Trace or TimeExecution
    // properties of the connection to profile execution.
    //
    // Parameters:
    // query:
    // The fully escaped SQL.
    //
    // args:
    // Arguments to substitute for the occurences of '?' in the query.
    //
    // Returns:
    // The number of rows modified in the database as a result of this execution.
    public Task ExecuteScalarAsync(string query, params object[] args);

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited September 4

    Set the second parameter to 'null'.

    public async Task SumItemAsync()
    {
        var data = await db.ExecuteScalarAsync("SELECT SUM(Amount) FROM Spent",null);
        return data;
    }
    
Sign In or Register to comment.