Tuesday, 27 August 2019

Sqlite SUM Entity value depending on LEFT JOIN value

I'm using Room on Android to query a POJO.

My POJO (Transaction) contains a value and an account_id. It further contains an account (instance of Account), which is fetched by a @Relation.

The accounts properties:

data class Account(
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = Database.Accounts.COL_ID) val id: Long = 0,
    @ColumnInfo(name = Database.Accounts.COL_NAME) val name: String = "",
    @ColumnInfo(name = Database.Accounts.COL_BALANCE) val balance: Double = 0.0
)

The accounts.balance is not a value in the database, but the sum of all transactions.value belonging to that account.

So I need to sum every transaction.value where transaction.account_id = account.id.

It should work similar to this way, but I'm not getting it right:

@androidx.room.Transaction
@Query(
    """
        SELECT transactions.* FROM transactions
        LEFT OUTER JOIN (SELECT transactions.value, SUM(transactions.value) AS balance FROM accounts) ON transactions.account_id = accounts.id
        GROUP BY transactions.id
"""
)
fun getTrs(): List<Transaction>



from Sqlite SUM Entity value depending on LEFT JOIN value

No comments:

Post a Comment