如何使用 ROOM 格式化查询
How to format Query using ROOM
所以我有一个包含 4 列的 table,我想对 amount
列的值求和,其中 isExpense
是 true
并且 isExpense
是 false
。我想减去这 2 个值和 return 那个总和。
除了单行查询外,我对 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>?
如果所有其他方法都失败了,我可以通过在 table 中创建更多列来解决这个问题。
使用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
所以我有一个包含 4 列的 table,我想对 amount
列的值求和,其中 isExpense
是 true
并且 isExpense
是 false
。我想减去这 2 个值和 return 那个总和。
除了单行查询外,我对 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>?
如果所有其他方法都失败了,我可以通过在 table 中创建更多列来解决这个问题。
使用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