1

Imagine I have this table:

tagId amount
1 100
1 150
2 200
2 250

And i need to sum the amount by grouping the tagId.

In SQL we can do this by: SELECT tagId, SUM(amount) FROM orders GROUP BY tagId;

Query result:

tagId SUM(amount)
1 250
2 450

How can I get such results in ObjectBox ?

Amin Mastani
  • 39
  • 1
  • 7

1 Answers1

2

There is no GROUP function in ObjectBox. Instead, write code to process query results in which ever way you desire. There are built-in property queries that can return a sum that may be helpful:

val sum = tagBox.query(Tag_.id.equals(id)).build()
    .property(Tag_.amount)
    .sumDouble()

Source: https://docs.objectbox.io/queries#propertyquery

Uwe - ObjectBox
  • 1,012
  • 1
  • 7
  • 11
  • Thanks for your help @uwe-objectbox . The problem is i have many Tags and i can't query each of them separately. Any thoughts? – Amin Mastani Jun 13 '22 at 11:12
  • 1
    Why not (e.g. use a property query to get all tag IDs with distinct() and findInts())? If performance is an issue I guess using find() and summing up results with your code is probably faster. It's also possible to use find with limit and offset to get results in batches if memory consumption is a concern. – Uwe - ObjectBox Jun 14 '22 at 05:39