You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Room数据库中按日期分组统计指定日期的总成本?

Room数据库按指定日期分组统计总成本实现

现有Room实体类对应的数据如下:

listOf(
    MyClass(id = 1, cost = 10, qty = 2, date = "10-10-2024"),
    MyClass(id = 2, cost = 11, qty = 1, date = "10-10-2024"),
    MyClass(id = 3, cost = 15, qty = 2, date = "11-10-2024"),
    MyClass(id = 4, cost = 20, qty = 3, date = "12-10-2024")
)

需实现方法getTotalCostOfDates(targetDates: List<String>),返回指定日期的分组总成本(每组为cost * qty的总和),预期返回:

listOf(
    CostClass(cost = 31, date = "10-10-2024"),
    CostClass(cost = 30, date = "11-10-2024")
)

1. 定义Room实体类(MyClass)

确保实体类正确映射数据库表:

@Entity(tableName = "my_table")
data class MyClass(
    @PrimaryKey val id: Int,
    val cost: Int,
    val qty: Int,
    val date: String
)

2. 定义结果数据类(CostClass)

用于接收分组统计结果,Room支持直接返回自定义数据类:

data class CostClass(
    val cost: Int,
    val date: String
)

3. DAO层编写查询方法

在DAO接口中添加带参数的分组查询,通过SUM(cost * qty)计算总成本,WHERE date IN (:targetDates)过滤指定日期,最后按date分组:

@Dao
interface MyDao {
    @Query("""
        SELECT SUM(cost * qty) AS cost, date 
        FROM my_table 
        WHERE date IN (:targetDates) 
        GROUP BY date
    """)
    suspend fun getTotalCostOfDates(targetDates: List<String>): List<CostClass>
}

4. 调用示例

在Repository或ViewModel中调用DAO方法:

// 假设已获取MyDao实例
val targetDates = listOf("10-10-2024", "11-10-2024")
val result = myDao.getTotalCostOfDates(targetDates)
// result即为预期的CostClass列表

内容的提问来源于stack exchange,提问作者laxus clive

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:22:42