我想计算表中所有记录的权重字段之和,我尝试过:
道课中
@Dao
interface FooDAO {
@Query("SELECT sum(purchaseWeight) FROM myTable")
suspend fun calculateSumOfAllWeight(): Int
}
在存储库类中
class FooRepository(application: Application) {
private var fooDAO: FooDAO
private var sumOfAllWeight = MutableLiveData<Int>()
init {
// skipping other code
CoroutineScope(Dispatchers.IO).launch {
sumOfAllWeight.postValue(fooDAO.calculateSumOfAllWeight())
}
}
fun getSumOfAllWeight(): MutableLiveData<Int> {
Log.e("SUM_OF_WEIGHT", " sumOfAllWeight "+ sumOfAllWeight.value)
return sumOfAllWeight
}
}
但是打印
E/SUM_OF_WEIGHT: sumOfAllWeight null
在logcat中,我已引用This Link在sqlite中使用sum()。
@Query("SELECT sum(purchaseWeight) as value FROM myTable")
suspend fun calculateSumOfAllWeight(): Int
找到This并更新
@Query("SELECT COALESCE(sum(COALESCE(purchaseWeight,0)), 0) From myTable")
suspend fun calculateSumOfAllWeight(): Int
但仍返回相同的null