【问题标题】:How to format Query using ROOM如何使用 ROOM 格式化查询
【发布时间】:2021-12-30 10:20:52
【问题描述】:

所以我有一个有 4 列的表,并且想对 amount 列的值求和,其中 isExpensetrue 并且 isExpensefalse。我想减去这两个值并返回那个总和。

除了单行查询之外,我没有太多的 SQL 经验,所以我很难格式化它。

         @Query("""
                SELECT SUM (amount) AS INCOME FROM `transaction` WHERE isExpense = 0,
                SELECT SUM (amount) AS EXPENSE FROM `transaction` WHERE isExpense = 1,
                SUM (INCOME - EXPENSE) AS BALANCE
                """)
    fun getTotalBalance(): Flow<Double>?

如果一切都失败了,我可以通过在我的表中创建更多列来解决这个问题。

【问题讨论】:

  • 您是否尝试过使用UNION
  • 请不要图片。改用格式化文本! (使复制和粘贴成为可能。我会在这里回答...)

标签: android sql kotlin android-room


【解决方案1】:

使用case表达式条件聚合

SELECT SUM(case when isExpense = 0 then amount else 0 end) AS INCOME,
       SUM(case when isExpense = 1 then amount else 0 end) AS EXPENSE,
       SUM(case when isExpense = 0 then amount
                when isExpense = 1 then -amount
           end) as BALANCE
FROM `transaction`

WHERE isExpense IN (0, 1) -- Not needed, but might speed things up if there
                          -- are other values than 0 and 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多